#=========================================== # Figure 14.7 vectorized.R. # R script to simulate investment with randomly # fluctuating prices many times and draw histogram # of final prices. # # An entire vector of log-prices is simulated # each time-interval, and stored as a column in a # matrix named x. The final column of the matrix # goes into the histogram. The approach eliminates # one of the for-loops in Figure 14.7.R. #=========================================== # Step 0. Initialization. days=60 # Time horizon of simulation (trading days). sim.num=1000 # Number of simulations. r=.06 # Annual average return of 6%. dt=1/124800 # 124800 minutes in 260 8-hr trading days # per year. sig=.2*r*sqrt(dt) # Spread constant for noise. mnts=days*8*60 # Number of minutes in 60 trading days. x=matrix(0,sim.num,mnts+1) # Matrix to contain the log-prices: # every row is a different simulation, # every column is a different time. t=numeric(mnts+1); # Vector to contain the accumulated times. # Step 1. Simulation. w=matrix(rnorm(mnts*sim.num,0,sig),sim.num,mnts) x[,1]=log(1000) # Initial investment amount. t[1]=0 # Initial time. for (i in 1:mnts) { dx=r*dt+w[,i] # Vector of changes in log-price during one minute. x[,i+1]=x[,i]+dx # Vector of new prices after one minute. t[i+1]=t[i]+dt # New accumulated time after one minute. } # Step 2. Plotting. prices=exp(x[,mnts+1]) # Change log-prices to prices. hist(prices,freq=FALSE) # Histogram.