library(quantmod)
getSymbols(‘MSFT’, from = ‘2007-01-01’, to = ‘2021-12-31’)
MSFT <- Ad(MSFT)
msftRetC <- monthlyReturn(MSFT, type = 'log')
Copyright By PowCoder代写 加微信 powcoder
mu <- mean(msftRetC); sigma.e <- sd(msftRetC) # parameters for model T <- length(msftRetC); # number of time periods for simulation set.seed(100) e <- rnorm(T, mean = 0, sd = sigma.e) # generate noise terms ret <- mu + e # calculate monthly return ret <- xts(ret, index(msftRetC)) # converting into xts format with dates # histogram of simulated returns hist(ret, freq = FALSE, ylim = c(0,6), breaks = 10, col = 'blue2') curve(dnorm(x, mu, sigma.e), -0.2, 0.2, add = TRUE, lwd = 2, col = 'red2') # Simulating Stock Price p0 <- as.numeric(log(MSFT[1])) # initial log price p <- p0 + mu * seq(T) + cumsum(e) # log price evolution over time p <- c(p0, p) # attach the initial log price to the front P <- exp(p) # going from log-price to price p <- xts(p, c(index(MSFT)[1], index(msftRetC))) # convert into xts format P <- xts(P, index(p)) # convert into xts format # Plot Simulated prices: plot(merge(p, P), multi.panel = TRUE, yaxis.same = FALSE, main= "Plot of Simulated Log-Price and Price") # Plot Actual Prices: plot(merge(log(MSFT), MSFT), multi.panel = TRUE, yaxis.same = FALSE, main= "Plot of Actual Log-Price and Price") # Try a different seed: set.seed(22) e <- rnorm(T, mean = 0, sd = sigma.e) # generate noise terms ret <- mu + e # calculate monthly return ret <- xts(ret, index(msftRetC)) # converting into xts format with dates # histogram of simulated returns hist(ret, freq = FALSE, ylim = c(0,6), breaks = 10, col = 'blue2') curve(dnorm(x, mu, sigma.e), -0.2, 0.2, add = TRUE, lwd = 2, col = 'red2') # Simulating Stock Price p0 <- as.numeric(log(MSFT[1])) # initial log price p <- p0 + mu * seq(T) + cumsum(e) # log price evolution over time p <- c(p0, p) # attach the initial log price to the front P <- exp(p) # going from log-price to price p <- xts(p, c(index(MSFT)[1], index(msftRetC))) # convert into xts format P <- xts(P, index(p)) # convert into xts format # Plot Simulated prices: plot(merge(p, P), multi.panel = TRUE, yaxis.same = FALSE, main= "Plot of Simulated Log-Price and Price") # Plot Actual Prices: plot(merge(log(MSFT), MSFT), multi.panel = TRUE, yaxis.same = FALSE, main= "Plot of Actual Log-Price and Price") # Multiple Simulations set.seed(100) e <- rnorm(T * 10, mean = 0, sd = sigma.e) e <- matrix(e, nrow=T) # organize into 10 sets of T values ret <- mu + e ret <- xts(ret, index(msftRetC)) # convert into xts form with dates # Now generate prices - same as before p0 <- as.numeric(log(MSFT)[1]) p <- p0 + apply(ret, 2, cumsum) p <- rbind(rep(p0, 10), p) # Attach initial price p <- xts(p, c(index(MSFT)[1], index(msftRetC))) #convert into xts with dates P <- exp(p) # actual price plot(P, main = "Plot of Simulated Price Paths") 程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com