After some useful comments about the previous post (see comments section in that post), here is the updated R code.
mysummary <- function(x){ s <- as.numeric(summary(x)) s[7] <- sd(x) s[8] <- sum(x <= 0) names(s) <- c("Min." , "1st Qu.", "Median" , "Mean" , "3rd Qu.", "Max." , "s.d." ,"No. of fails" ) round(s, digits = 0) } years <- seq(1900, 2015) ret <- c(0.115,-0.035,0.035,0.018,0.123,0.038,0.186,-0.089,0.019,0.109,0.021,-0.015,0,-0.034,-0.005, -0.17,-0.173,-0.096,0.05,0.074,-0.34,0.34,0.393,0.028,0.176,0.173,0.055,0.148,0.173,-0.141, 0.031,-0.162,0.383,0.248,0.13,0.116,0.159,-0.177,-0.079,-0.079,-0.153,0.192,0.184,0.121,0.113, 0.048,0.173,-0.053,-0.083,-0.089,0.074,-0.031,-0.061,0.229,0.429,0.048,-0.117,-0.055,0.452, 0.548,-0.001,-0.025,-0.022,0.177,-0.098,0.066,-0.074,0.311,0.398,-0.159,-0.105,0.344,0.081, -0.35,-0.581,0.996,-0.111,0.325,0.002,-0.049,0.171,0.013,0.219,0.223,0.258,0.137,0.227,0.048, 0.044,0.258,-0.174,0.157,0.168,0.251,-0.086,0.192,0.131,0.193,0.106,0.217,-0.086,-0.138,-0.245, 0.169,0.088,0.189,0.114,0.01,-0.304,0.259,0.089,-0.078,0.087, 0.174, -0.004, -0.001) muret <- mean(ret) sdret <- sd(ret) ## These are the variables to change I0 <- 600 ## starting capital nyrs <- 30 ## Number of years that money needs to last spend <- 20 ## Annual expenditure by <- c(0:5) ## buffer as years of expenditure ########## CBfin <- NULL Ifin <- NULL smryI <- NULL smryCB <- NULL ## ret <- 0.04 For testing only!! for(k in 1:length(by)){ CB0 <- by[k]*spend I0 <- I0 - CB0 ## Model now has constant total wealth for(j in 1:10000){ I <- I0 CB <- CB0 for(i in 1:nyrs){ r <- sample(ret, 1) ## r <- rnorm(1,muret,sdret) ## Alternative way of estimating future return ## First section recalculates capital given earnings and spending e <- r*I ## e = earnings if((I+e)>=(I0+spend)){ I <- I+e-spend ### If there is sufficient earnings to cover expenditure use that }else{ if(CB>=spend){ CB <- CB-spend ### If there isn't use the cash buffer I <- I+e ### This is what I forgot. Even though you haven't touched the capital it still needs to change }else{ I <- I + e + CB - spend ## if all else fails you eat into the capital and exhaust your cash buffer. I'd forgotten to include e in this. CB <- 0 } } ## Second section recalculates cash buffer if((CB < CB0) & (I > I0)){ ### Not enough cash in the buffer but excess capital CB <- CB+I-I0 ### increase cash buffer by the growth in the capital I <- I0 ### Set capital back to initial figure if(CB >= CB0){ CB <- CB0 ### If there is now too much cash in the buffer reinvest the excess I <- I + CB - CB0 } } if(I<=0){ I <- 0 break } } CBfin[j] <- CB Ifin[j] <- I } smryI[[k]] <- mysummary(Ifin) smryCB[[k]] <- mysummary(CBfin) } completesmryI <- do.call("rbind", smryI) rownames(completesmryI) <- paste(by, "Year(s)") completesmryI completesmryCB <- do.call("rbind", smryCB) rownames(completesmryCB) <- paste(by, "Year(s)") completesmryCB
Advertisements