Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require(quantmod)
- ############ Part 1 #############
- ######### Create framework for getting data #########
- ### Get number of securities user wants to backtest
- number.of.securities <- as.numeric(readline('Enter number of securities to backtest: '))
- ### Get years to backtest
- backtest.period <- as.numeric(readline('Enter years to backtest: '))
- ####### Get symbols for n number of securities
- #create matrix for quotes
- symbol.matrix <- matrix(ncol = number.of.securities)
- symbol.weight.matrix <- matrix(ncol = number.of.securities)
- #get symbols
- for (i in 1:number.of.securities){
- symbol.matrix[i] <- readline('Enter symbol: ')
- symbol.weight.matrix[i] <- as.numeric(readline('Enter weight: '))
- }
- #use symbol.matrix to get data
- #create empty variable for storing data
- data.matrix <- NULL
- # loop through symbol matrix and get data using getSymbols
- for (i in 1:number.of.securities){
- v <- na.omit(ROC(Cl(getSymbols(symbol.matrix[i], from = Sys.Date() - (365*backtest.period), auto.assign = FALSE))))
- data.matrix <- cbind(data.matrix, v)
- }
- ########## Part 2 ############
- ####### Backtest data ###########
- starting.amount <- 10000
- ###Create starting amount for each equity
- starting.equity.matrix <- matrix(ncol = number.of.securities)
- for (i in 1:number.of.securities){
- starting.equity.matrix[,i] <- symbol.weight.matrix[,i] * starting.amount
- }
- # Calc cumsum of each security to find equity curve
- equity.curve.matrix <- matrix(ncol = number.of.securities, nrow = length(data.matrix[,1]))
- for (i in 1:number.of.securities){
- equity.curve.matrix[,i] <- exp(cumsum(data.matrix[,i]))
- }
- ##### 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
- equity.performance.matrix <- matrix(ncol = number.of.securities, nrow = length(data.matrix[,1]))
- for (i in 1:number.of.securities){
- equity.performance.matrix[,i] <- equity.curve.matrix[,i] * starting.equity.matrix[,i]
- }
- ### Now we need to combine the equity performance columns
- total.performance <- as.matrix(rowSums(equity.performance.matrix))
- # Putting the dates back on the matrix
- dates <- data.matrix[,0]
- total.performance <- merge(dates, total.performance)
- plot(total.performance, type = 'l')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement