#=========================================== # Figure 14.7.R. # R script to simulate investment with randomly # fluctuating prices many times and draw histogram # of final prices. #=========================================== # 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=numeric(mnts+1) # Vector to contain the log-prices. t=x; # Vector to contain the accumulated times. log.prices=numeric(sim.num) # Step 1. Simulation. w=matrix(rnorm(mnts*sim.num,0,sig),sim.num,mnts) for (h in 1:sim.num) { x[1]=log(1000) # Initial investment amount. t[1]=0 # Initial time. for (i in 1:mnts) { dx=r*dt+w[h,i] # Change in log-price during one minute. x[i+1]=x[i]+dx # New price after one minute. t[i+1]=t[i]+dt # New accumulated time after one minute. } log.prices[h]=x[mnts+1] # Last log-price in x } # Step 2. Plotting. prices=exp(log.prices) # Change log-prices to prices. hist(prices,freq=FALSE) # Histogram.