#=========================================== # Figure 14.6.R. # R script to simulate investment with randomly # fluctuating prices. #=========================================== # Step 0. Initialization. days=60 # Time horizon of simulation (trading days). r=.06 # Annual average return of 6%. dt=1/115200 # 115200 minutes in 240 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. x[1]=log(1000) # Initial investment amount. t[1]=0 # Initial time. # Step 1. Simulation. w=rnorm(mnts,0,sig) # Generate vector of normal noises outside # the loop (more efficient) for (i in 1:mnts) { dx=r*dt+w[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. } # Step 2. Plotting. n=exp(x) # Change log-prices to prices. plot(t,n,type="l") # Plot prices vs time.