# Future Value Calculations
V <- 1000; R <- 0.03; n <- c(3, 5, 10)
FV <- V * (1 + R)^n
# Solving for R
Copyright By PowCoder代写 加微信 powcoder
V <- 1000; FV <- 2000; n <- 10 R <- (FV / V)^(1/n) - 1 # Solving for n V <- 1000; FV <- 2000; R <- seq(0.01, 0.20, 0.01) n <- log(FV / V) / log(1 + R) 0.70 / R # Rule of 70 cbind(R, n, 0.70 / R) # cbind for binding vertically # Multiple Compounding Periods V <- 1000; R <- 0.03; n <- 1; m <- c(1, 2, 3, 4, 12, 52, 365) FV <- V * (1 + R / m) ^ (m * n) cbind(m, FV) # Continuous compounding V * exp(R * n) plot(m, FV) # Import Data WMT <- read.csv("~/Downloads/WMT.csv") WMT <- WMT[, c(1,6) ] # Only keep date & adjusted closing price names(WMT)[2] <- "P" # rename adjusted closing price to P # Simple net monthly return WMT$R <- WMT$P[-1] / WMT$P - 1 WMT$R[60] <- NA # Throw away the last return because it's invalid # Continuous Compounded Returns WMT$r <- log(1 + WMT$R) # using definition of log return head(WMT) # view first few rows of data tail(WMT) # view last few rows of data # Invest $1 in WMT. How does it grow over time? WMT$cumR <- cumprod(1 + WMT$R) # Arithmetic Average sum(WMT$R, na.rm = TRUE) / (length(WMT$R) - 1) mean(WMT$R, na.rm = TRUE) # Geometric Average WMT$cumR[length(WMT$R) - 1] ^ (1 / (length(WMT$R) - 1)) - 1 (WMT$P[length(WMT$P)] / WMT$P[1]) ^ (1 / (length(WMT$R) - 1)) - 1 plot(WMT$cumR) # Plot value of $1 as it grows WMT$Date <- as.Date(WMT$Date) # Convert 1st column into Date format plot(WMT$Date, WMT$cumR, type = 'l') # Plot with date on horizontal axis # Using quantmod for stock data library(quantmod) getSymbols('AAPL') # download AAPL data from Yahoo finance # Alternate data source: quandl head(AAPL) # Plotting tool within quantmod chartSeries(AAPL) # What type of object is AAPL? class(AAPL) # How are dates stored in AAPL? index(AAPL) # Dates are stored as an index!!! # Working with dates: AAPL['2021-04-30'] # for getting data on a specific date AAPL['2021-04-30/'] # getting data from a date AAPL['/2007-04-30'] # getting data until a date AAPL['2021-09'] # getting data on a specific month AAPL['2021-01/2021-03'] # 1st quarter of 2021 AAPL['2021'] # getting data on a specific year # can change from daily to monthly: AAPL <- to.monthly(AAPL) head(AAPL) # Calculate returns again AAPL <- AAPL[,6] names(AAPL) <- "P" AAPL <- AAPL['2021'] # keeping only 2021 AAPL$lag.P <- lag(AAPL$P) # simple net return AAPL$R <- AAPL$P / AAPL$lag.P - 1 AAPL$diff.P <- diff(AAPL$P) AAPL <- na.omit(AAPL) # removes rows with any NA values # multiple stocks getSymbols(c('NFLX', 'META')) 程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com