1

I (being an absolut beginner with R and programming) have to do some analysis with R for my thesis in finance :( The purpose is to simulate data (stock prices) with a GBM and run over the results 2 trading strategies. Within the GBM I'll have to "play" with the veriables "r" and "sigma" (3 different values for each, thus 9 combinations). Each combination needs to be simulated 10000 times over a period T=10, N=250. To all these simulations 2 trading strategies have to be applied - MACD and RSI (within the TTR-package). Now I'm facing an issue with writing the code :(

#Geometrical Brownian Motion
Sim <- GBM(x, r, sigma, T, N)
x <-100
r <-0
sigma <-1
T <- 10
N <- 250

#Additional info for RSI-strategy
retSim <- ROC(Sim)
SimRSI <- RSI(Sim, 14,)
SimRSI[is.na(SimRSI)] <- 0

#Create a vector for the results of the inner loop
portfolio <- rep(0:N)
portfolio[1] <- 100

runs <- 10000

#Creating vectors for final results of portfolio and simulation after 10000 runs (only the last value of each of the 10000 simulations and portfolio results of the strategy required)
resultsSimGBM <- rep(0:runs)
resultsRSIr1sig1 <- rep(0:runs)

#orders
buyRSI<-portfolio[i-1]*exp(retSim[i])
holdRSI<-portfolio[i-1]

#Simulation
portfolio[1]<-100
i <- 1
j <- 1

#Second loop
for(j in 0:runs){

  #Simulation GBM

  x <-100
  r <-0
  sigma <-1
  T <- 10
  N <- 250
  Sim <- GBM(x, r, sigma, T, N)
  retSim <- ROC(Sim)
  SimRSI <- RSI(Sim, 14,)
  SimRSI[is.na(SimRSI)] <- 0
  portfolio[1] <- 100

  #First loop
  for(i in 2:length(Sim)){

    #Apply RSI on GBM
    buyRSI<-portfolio[i-1]*exp(retSim[i])
    holdRSI<-portfolio[i-1]

    if(SimRSI[i-1]<50 && SimRSI[i]>50){portfolio[i]=buyRSI}
    if(SimRSI[i-1]>50 && SimRSI[i]<50){portfolio[i]=holdRSI}
    if(SimRSI[i-1]<50 && SimRSI[i]<50){portfolio[i]=holdRSI}
    if(SimRSI[i-1]>50 && SimRSI[i]>50){portfolio[i]=buyRSI}
    i <- i+1
  }
  resultsRSI[j] <- portfolio[N]
  resultsSimGBM[j] <- Sim[N]
  j <- j+1
}

Anyway, this is what I have until now and it seems to work. However, into the first (inner) loop, I need to include also the second strategy (which until now, singled out) looked following :

#MACD strategy
portfolioMACD[1]<-100
i <- 1
j <- 1

for(j in 0:runs){
  Sim <- BMSim
  retSim <- ROC(Sim)
  SimMACD <- MACD(Sim, 12, 26, 9, myType="EMA")
  DataSimMACD <- data.frame(SimMACD)
  DataSimMACD$macd[is.na(DataSimMACD$macd)] <- 0
  DataSimMACD$signal[is.na(DataSimMACD$signal)] <- 0

for(i in 2:length(Sim)){
  buyMACD<-portfolioMACD[i-1]*exp(retSim[i])
  sellMACD<-portfolioMACD[i-1]
  holdMACD<-portfolioMACD[i-1]*exp(retSim[i])
  if(DataSimMACD$macd[i-1]<DataSimMACD$signal[i-1] && DataSimMACD$macd[i]>DataSimMACD$signal[i]){portfolioMACD[i]=buyMACD}
  if(DataSimMACD$macd[i-1]>DataSimMACD$signal[i-1] && DataSimMACD$macd[i]<DataSimMACD$signal[i]){portfolioMACD[i]=sellMACD}
  if(DataSimMACD$macd[i-1]>DataSimMACD$signal[i-1] && DataSimMACD$macd[i]>DataSimMACD$signal[i]){portfolioMACD[i]=holdMACD}
  if(DataSimMACD$macd[i-1]<DataSimMACD$signal[i-1] && DataSimMACD$macd[i]<DataSimMACD$signal[i]){portfolioMACD[i]=sellMACD}
  if(DataSimMACD$macd[i]==DataSimMACD$signal[i]){portfolioMACD[i]=sellMACD}
  if(DataSimMACD$macd[i-1]==DataSimMACD$signal[i-1] && DataSimMACD$macd[i]!=DataSimMACD$signal[i]){portfolioMACD[i]=buyMACD}
  i <- i+1
}
  resultsMACD[j] <- portfolioMACD[length(Sim)]
  j <- j+1
}

BASICALLY: 1-One Brownian motion has to consist of 2500 elements, to which both trading strategies have to be applied separately 2-this whole procedure has to be repeated 10000 times for each out of 9 combinations of variables r and sigma (r1sigma1, r1sigma2, r1sigma3,.....,r3sigma3) (this I don't have included in my code yet - no clue how to construct those 2 loops around it all...) :( 3-the endresult should be a 10000x27 matrix with 10000rows (for amount of runs) and 27 colums (9x GBM, RSI, MACD) filled only with the 2500th (endvalue) of each simulation (from point 1.) --> how to do it?

SOS! Could someone of you PLEASE PLEASE PLEASE help me with this mess? I'm completely lost and it's my graduation paper -.-

Every help will be highly praised and deeply appreciated!

Thanks in advance and sorry for the long post.

Cheers from Berlin, Ana :)

EDIT AND ANOTHER SIMPLIFIED EXAMPLE

    library(sde)

    #Vectors for results
    Returns <- rep(0:N)
    LogReturns <- rep(0:N)
    Simulation <- rep(0:N)
    ResultsSimulation <- rep(0:runs)
    ResultsReturns <- rep(0:runs)
    ResultsLog <- rep(0:runs)

    runs=50   #how ofthen the Simulation of GBM should be repeated
    i <- 1
    j <- 1

    #second loop
    for(j in 2:runs){
      Simulation <- GBM(x, r, sigma, T, N)
      x=100
      r=0
      sigma=1
      T=1
      N=20

    #first loop
      for(i in 2:length(BM)){
        Returns <- ROC(Simulation)
        LogReturns[i+1] <- log(Simulation[i+1]/Simulation[i])

        i <- i+1
      }
      ResultsSimulation[j]<-Simulation[N]
      ResultsReturns[j]<-Returns[N]
      ResultsLog[j]<-LogReturns[N]

      j <- j+1
    }

ResultsMatrix <- as.matrix(data.frame(ResultsSimulation, ResultsReturns, ResultsLog))

The structure of this example is basically what I have. I need to construct around it 2 more loops which will do the same simulations and calculations for 3 different "r" values and "sigma" values (variables within the GBM-function). The resuls (the final value of each Simulation and calculation from the first loop) should be saved in separate vectors or in a matrix consisting of those --> thus, 27 vestors of length 50 (3 results for each combination of variables r and sigma) for example, if sigma=0.1; 0.3; 0,6 and r=0,03; 0,05; 0,08

How to construct those loops around it all and save the data accordingly?

Sorry for the questions guys, but I'm really lost :(

Cheers and thanks a lot in advance! At least for reading ;)

AnaBanana
  • 33
  • 1
  • 4
  • 3
    You should provide a minimal example: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example, not your full graduation paper work. – Ricardo Oliveros-Ramos Jun 27 '13 at 20:04
  • It will be easier for us if you can zoom into the precise problem you are having as @Ricardo mentioned above. – asb Jun 27 '13 at 20:33
  • Hey there, sorry for the huge initial post, I added a simplified example... I hope it's better now... cheers :) – AnaBanana Jun 28 '13 at 13:12
  • This is basic programming, i can help you if you provide a complete 'flow' of what you need to do - it's very hard to read all of this. – Fernando Jul 02 '13 at 15:16

1 Answers1

1

Is this close to what you need? If so, you can add new trading functions to return a portfolio, then just call it (see the example):

warning: It took about 1.5 hours to run with N_SIMS = 100000!

get.simulation.GBM = function(TIME = 10, N = 250, N_SIMS = 1000, x0 = 100, sigma = c(0.1, 0.3, 0.6), r = c(0.03, 0.05, 0.08))
{
  require(sde)
  params = expand.grid(sigma = sigma, r = r)
  
  # pre-allocate matrix
  results = matrix(0, ncol = N_SIMS * nrow(params), nrow = N)
  
  for (i in 1:nrow(params))
  {
    idx.range =  ((i - 1)*N_SIMS + 1):((i - 1)*N_SIMS + N_SIMS)
    temp.res = replicate(N_SIMS, GBM(x0, r = params[i, 'r'], sigma = params[i, 'sigma'], T = TIME, N = N - 1 ))
    results[, idx.range] = temp.res
  }
  
  return(results)
}

apply.MACD = function(serie, nFast = 12, nSlow = 26, nSig = 9, p0 = 100)
{
  require(TTR)
  roc = ROC(serie)
  sim.MACD = MACD(serie, nFast, nSlow, nSig, maType = "EMA")
  portfolio = rep(0, length = length(serie))
  portfolio[1] = p0
  
  sim.MACD[is.na(sim.MACD)] = 0
  sim.MACD = as.data.frame(sim.MACD)
  
  for (i in 2:length(serie))
  {
    buy = portfolio[i - 1] * exp(roc[i])
    sell = portfolio[i - 1]
    hold = buy
    
    if(sim.MACD$macd[i - 1] < sim.MACD$signal[i - 1] && sim.MACD$macd[i] > sim.MACD$signal[i]){portfolio[i] = buy}
    if(sim.MACD$macd[i - 1] > sim.MACD$signal[i - 1] && sim.MACD$macd[i] < sim.MACD$signal[i]){portfolio[i] = sell}
    if(sim.MACD$macd[i - 1] > sim.MACD$signal[i - 1] && sim.MACD$macd[i] > sim.MACD$signal[i]){portfolio[i] = hold}
    if(sim.MACD$macd[i - 1] < sim.MACD$signal[i - 1] && sim.MACD$macd[i] < sim.MACD$signal[i]){portfolio[i] = sell}
    if(sim.MACD$macd[i] == sim.MACD$signal[i]){portfolio[i] = sell}
    if(sim.MACD$macd[i - 1] == sim.MACD$signal[i - 1] && sim.MACD$macd[i] != sim.MACD$signal[i]){portfolio[i] = buy}
    
  }
  return(portfolio)
}

apply.RSI = function(serie, p0 = 100, n = 14)
{
  require(TTR)
  roc = ROC(serie)
  sim.RSI = RSI(serie, n = n)
  sim.RSI[is.na(sim.RSI)] = 0
  portfolio = rep(0, length = length(serie))
  portfolio[1] = p0
  
  for (i in 2:length(serie))
  {
    buy = portfolio[i - 1] * exp(roc[i])
    hold = portfolio[i - 1]
    
    if(sim.RSI[i - 1] < 50 && sim.RSI[i] > 50){portfolio[i] = buy}
    if(sim.RSI[i - 1] > 50 && sim.RSI[i] < 50){portfolio[i] = hold}
    if(sim.RSI[i - 1] < 50 && sim.RSI[i] < 50){portfolio[i] = hold}
    if(sim.RSI[i - 1] > 50 && sim.RSI[i] > 50){portfolio[i] = buy}
  }
  return(portfolio)
}

# Example (this is SLOW)
simulation.matrix = get.simulation.GBM()
portfolio.RSI = apply(simulation.matrix, 2, apply.RSI)
portfolio.MACD = apply(simulation.matrix, 2, apply.MACD)

# if you need only the last values
portfolio.RSI.last = tail(portfolio.RSI, 1)
portfolio.MACD.last = tail(portfolio.MACD, 1)
Community
  • 1
  • 1
Fernando
  • 7,785
  • 6
  • 49
  • 81
  • Hi Fernando! Thanks for the answer! It comes close to what I need. How can I run x (in your code 50) simulations for each combination of parameters? Now it gives me a 250x50 matrix with all the values of the simulated GBM (and I also don't know which simulation used which parameters) Basically, I need to simulate a GBM, run over it 2 formulas (2 investment strategies), save only the last value of each of the 3 vectors (GBM and 2 strategies). This needs to be done x (in my case specifically 10.000) times for each combination of parameters. Is it doable without losing the overview? cheers :) – AnaBanana Jul 03 '13 at 16:12
  • Hum... the problem is i don't know what you mean by 'apply the trading strategy'. The best approach is to create a separate function to each strategy, then use *replicate()* on it. Can you describe briefly how these strategies work? (i dont know nothing about finances!) – Fernando Jul 03 '13 at 17:41
  • The thing is, I already have a ready code for the GBM and the application of the strategies. I don't know how to expand the code to do the same for all the other combinations of parameters and how to save it nicely... Basically, a GBM is simulated, then (for 1 strategy) a function (RSI) is applied on that GBM which calculates the RSI-index. Based on the index and conditions written by me (e.g. if RSI[i-1]<50 && RSI[i]>50 then simulatedRSI[i]=..........and so on) a vector is created where according to those conditional rules commands are executed ("buy", "sell" etc). I need only the last ..... – AnaBanana Jul 03 '13 at 18:28
  • .....value of the GBM and those created vectors (after executing the commands). The whole procedure is done for one combination of variables (r and sigma) x (10.000) times, recording only the last value. Then again 10000 simulations, applying the strategies with another pair of variables etc... I could run the same thing, what I already have 9 times, but it would be nice to have it as a ready program and do it in one go... Another issue for me is how to store the data in one matrix (27 vectors of length 10000) or just 9 separate matrices of 3 vectors each... – AnaBanana Jul 03 '13 at 18:32
  • I need to run both strategies over the same 10000(x9) GBMs – AnaBanana Jul 03 '13 at 18:33