calculate returns for a financial time series with trading signals

779 views Asked by At

I have a financial time series data for which i want to calculate Returns , Maximum Draw down etc based on a signal series . My actual time series is a big one. I am giving here a toy example so that i can tell want i need. Here 1 is for buy signal and -1 is for sell signal. I initiate and hold the trade position till the opposite signal is received and then reverse the position ans so on. Returns should be calculated for every data point so that an Equity Curve can be plotted.

data<- rnorm(20,100,3)
signal<- c( 1,1,1,1,1,1,1,-1,-1,-1,-1,-1,1,-1,1,-1,-1,-1,-1,1)

For this purpose Quantmod and PerformanceAnalytics comes to my mind.

Any help appreciated.

1

There are 1 answers

1
Usobi On

I have no idea of the R financial packages (I wish I knew). I am guessing that your main problem is to know when to trade and when not to trade, and, that after figuring out that, your problem is solved.

First you may try with a pure R solution. I am a fan of Reduce so you may try with this.

deltaTrade <- function(currentTrend,nextSignal) ifelse(lastOp != nextSignal,1,-1)
trade <- Reduce('deltaTrade',signal,init=signal[1],accumulate=TRUE)
tradePeriods = which(trade==1)

If it is too slow I have recently seen in other SO questions that switching to C++ for an efficient solution is a good way to tackle the problem. You can do that with the cpp package, which apparently has become a real hip.

library(Rcpp)

cppFunction("NumericVector selectTrades(NumericVector x, NumericVector out) {
  int n = x.length();
  int current = x[0];
  for(int i = 0; i < n; ++i) {
    if (x[i] == current) {
      out[i] = 0; // hold position
    } else {
      current = x[i];
      out[i] = 1; // play position
    }
  }
  return out;
}")

trades = which(selectTrades(signal,out)==1)

Anyway, I hope that any of these helps.