Now, let’s try some parameter optimisation for the SMA strategy! There probably are functions out there on R which I can use to do this, but I figured it would take me as long to actually code it as it would to find something usable on the internet, and I enjoy coding much more than looking stuff up on the internet.

My aim is to find out which SMA is the best to use for going long, and which SMA is the best to use for going short on the S&P 500. Ideally, I should optimize the short SMA for each long SMA (or vice-versa) to find the best combination, but I don’t think optimizing them independently (as I did here) would make much of a difference in this case. This is the code I wrote:

optimizeSMA=function(mainVector,returnsVector,smaInit=3,smaEnd=200,long=TRUE){ bestSMA=0 bestSharpe=0 for( i in smaInit:smaEnd){ smaVec=SMA(mainVector,i) if(long==T){ binVec=lag(ifelse(mainVector>smaVec,1,0),1) binVec[is.na(binVec)]=0 stratRets=binVec*returnsVector sharpe=SharpeRatio.annualized(stratRets, scale=252) if(sharpe>bestSharpe){ bestSMA=i bestSharpe=sharpe } }else{ binVec=lag(ifelse(mainVector<smaVec,-1,0),1) binVec[is.na(binVec)]=0 stratRets=binVec*returnsVector sharpe=SharpeRatio.annualized(stratRets, scale=252) if(sharpe>bestSharpe){ bestSMA=i bestSharpe=sharpe } } } print(cbind(bestSMA, bestSharpe)) }

Created by Pretty R at inside-R.org

It is pretty straight-forward and self-explanatory. It initiates a loop which goes through each SMA from smaInit to smaEnd and stores the one with the highest Sharpe ratio. For more complicated strategies, we will need to do a little bit more heavy-lifting when it comes to parameter optimization. This code maximizes the Sharpe ratio, but you can easily modify it to maximize returns, minimize volatility, etc. The highest Sharpe ratio SMA to use for the long position is the 70-Day SMA and for the short position is the 84-day SMA.

After running the strategy with the optimized parameters, these are the performance results:

**Optimized:**

Cumulative Return: 0.31104898 Annual Return: 0.04286661

Annualized Sharpe Ratio: 0.18405777 Win %: 0.53078556

Annualized Volatility: 0.23289757 Maximum Drawdown: -0.28943309

Max Length Drawdown: 1078.00000000

Not a huge difference from what we had before. And the little bit of performance improvement that we achieved is probably more a result of curve-fitting than anything else. If your initial parameter values conform with some market intuition -and thus capture most of the obtainable market return- parameter optimization will not be that helpful in a paper-trading implementation of your strategy, as the improvements will mostly be due to curve-fitting the historical data.