Advertisement
Guest User

Portfolio backtester

a guest
Jan 13th, 2013
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 2.27 KB | None | 0 0
  1. require(quantmod)
  2.  
  3.  
  4. ############ Part 1 #############
  5. ######### Create framework for getting data #########
  6.  
  7. ### Get number of securities user wants to backtest
  8. number.of.securities <- as.numeric(readline('Enter number of securities to backtest: '))
  9.  
  10. ### Get years to backtest
  11. backtest.period <- as.numeric(readline('Enter years to backtest: '))
  12.  
  13. ####### Get symbols for n number of securities
  14.  
  15. #create matrix for quotes
  16. symbol.matrix <- matrix(ncol = number.of.securities)
  17. symbol.weight.matrix <- matrix(ncol = number.of.securities)
  18.  
  19. #get symbols
  20. for (i in 1:number.of.securities){
  21.   symbol.matrix[i] <- readline('Enter symbol: ')
  22.   symbol.weight.matrix[i] <- as.numeric(readline('Enter weight: '))
  23. }
  24.  
  25.  
  26. #use symbol.matrix to get data
  27. #create empty variable for storing data
  28. data.matrix <- NULL
  29.  
  30. # loop through symbol matrix and get data using getSymbols
  31. for (i in 1:number.of.securities){
  32.   v <- na.omit(ROC(Cl(getSymbols(symbol.matrix[i], from = Sys.Date() - (365*backtest.period), auto.assign = FALSE))))
  33.   data.matrix <- cbind(data.matrix, v)
  34. }
  35.  
  36.  
  37. ########## Part 2 ############
  38. ####### Backtest data ###########
  39.  
  40.  
  41. starting.amount <- 10000
  42.  
  43. ###Create starting amount for each equity
  44.  
  45. starting.equity.matrix <- matrix(ncol = number.of.securities)
  46.  
  47. for (i in 1:number.of.securities){
  48.   starting.equity.matrix[,i] <- symbol.weight.matrix[,i] * starting.amount
  49. }
  50.  
  51. # Calc cumsum of each security to find equity curve
  52.  
  53. equity.curve.matrix <- matrix(ncol = number.of.securities, nrow = length(data.matrix[,1]))
  54.  
  55. for (i in 1:number.of.securities){
  56.   equity.curve.matrix[,i] <- exp(cumsum(data.matrix[,i]))  
  57. }
  58.  
  59. ##### Now we have the equity curves, we can apply the starting amounts for each equity to each curve and find the gain/loss through time
  60.  
  61. equity.performance.matrix <- matrix(ncol = number.of.securities, nrow = length(data.matrix[,1]))
  62.  
  63. for (i in 1:number.of.securities){
  64.   equity.performance.matrix[,i] <- equity.curve.matrix[,i] * starting.equity.matrix[,i]
  65. }
  66.  
  67.  
  68. ### Now we need to combine the equity performance columns
  69. total.performance <- as.matrix(rowSums(equity.performance.matrix))
  70.  
  71. # Putting the dates back on the matrix
  72. dates <- data.matrix[,0]
  73. total.performance <- merge(dates, total.performance)
  74.  
  75. plot(total.performance, type = 'l')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement