---
title: "Return Calculations in R"
author: "Eric Zivot"
subtitle: ECON 424
output: slidy_presentation
---

## Set Options and Load Packages

```{r}
# set options and load packages
options(digits = 3)
options(width = 75)
Sys.setenv(TZ="UTC")
library(dygraphs)
library(IntroCompFinR)
library(PerformanceAnalytics)
library(xts)
```

## Future Value Calculations

Calculate future value of $1000 after 1, 5 and 10 years assuming 3% return per year.

```{r}
V = 1000
R = 0.03
FV1 = V*(1 + R)
FV5 = V*(1 + R)^5
FV10 = V*(1 + R)^10
```

```{r}
FV1
FV5
FV10
```

## Rule of 70

Calculate how long it takes to double your money at different interest rates.

```{r}
# create sequence of interest rates
R = seq(0.01, 0.10, by=0.01)
R
# Commpute time it takes for investment to double in value: Exact calculation
n = log(2)/log(1 + R)
names(n) = R
n
# Commpute time it takes for investment to double in value: rule of 70
n = 0.7/R
names(n) = R
n
```

## Multiple Compounding Periods

Calculate future value of $1000 after 1 year with different compounding periods.

```{r}
V = 1000
R = 0.1
m = c(1, 2, 4, 356, 10000)
FV = V*(1 + R/m)^(m)
RA = FV/V - 1
names(FV) = names(RA) = m
print(FV, digits=4)
print(RA, digits=4)
```

## Simple 1-Month Return on Microsoft Stock

Invest in Microsoft stock for 1 month and calculate simple return.

```{r}
# prices
P0 = 90
Pm1 = 85
# 1-month net and gross return
R = (P0 - Pm1)/Pm1
R
1 + R
```

## Simple 2-Month Returns on Microsoft Stock

Invest in Microsoft stock for 2 months and calculate simple return.

```{r}
# price 2 periods back
Pm2 = 80
# 2-month net and gross return
R.2 = (P0 - Pm2)/Pm2
R.2
1 + R.2
```


## Vectorized Calculations

Calculate 1 period returns from a vector of prices.

```{r}
# vector of prices
P = c(Pm2, Pm1, P0)
# calculate vector of 1-month returns from vector of prices
R = (P[2:3] - P[1:2])/P[1:2]
R 
# calculate 2-month return from 2 1-month returns
(1 + R[1])*(1 + R[2]) - 1
# same calculation vectorized using R function cumprod()
cumprod(1+R) - 1
```

## Portfolio Returns

Calculate 1 month return on portfolio with 10 shares of stock in Microsoft and 10 shares of stock in Starbucks. 

```{r}
# prices
P.msft = c(85, 90)
P.sbux = c(30, 28)
# initial wealth
V = P.msft[1]*10 + P.sbux[1]*10
V
# portfolio weights
x.msft = P.msft[1]/V
x.msft
x.sbux = P.sbux[1]/V
x.sbux
# asset returns
R.msft = (P.msft[2] - P.msft[1])/P.msft[1]
R.msft
R.sbux = (P.sbux[2] - P.sbux[1])/P.sbux[1]
R.sbux
# portfolio return
R.p = x.msft*R.msft + x.sbux*R.sbux
R.p
```


## Example Data - SBUX Monthly Prices

```{r}
# load daily data from IntroCompFinR - xts object
data(sbuxDailyPrices)
# pick off end-of-month prices using xts function to.monthly()
sbuxMonthlyPrices = to.monthly(sbuxDailyPrices, OHLC=FALSE)
class(sbuxMonthlyPrices)
str(sbuxMonthlyPrices)
```

## Example Data

```{r}
head(sbuxMonthlyPrices, n=3)
tail(sbuxMonthlyPrices, n=3)
colnames(sbuxMonthlyPrices)
```

## Extract Data and Time Index

```{r}
# coredata() extracts data
head(coredata(sbuxMonthlyPrices), n=3)
# index() extracts time index
head(index(sbuxMonthlyPrices), n=3)
```

## Plot Monthly Closing Prices

```{r}
plot.zoo(sbuxMonthlyPrices, main="Monthly Prices on SBUX",
         lwd = 2, col="blue", ylab="Price")
```

## Compute Monthly Simple Returns

```{r}
sbuxRet = diff(sbuxMonthlyPrices)/lag(sbuxMonthlyPrices)
head(sbuxRet, n=3)
# remove first NA observation
sbuxRet = sbuxRet[-1]
head(sbuxRet, n=3)

```

## Calculate Monthly CC Returns

```{r}
# compute from simple returns
sbuxRetC = log(1 + sbuxRet)
head(sbuxRetC, n=3)

# compute directly from prices
sbuxRetC = diff(log(sbuxMonthlyPrices))
sbuxRetC = sbuxRetC[-1]
head(sbuxRetC, n=3)
```


## PerformanceAnalytics Package

```{r}
# Simple returns using Return.calculate()
sbuxRet = Return.calculate(sbuxMonthlyPrices)
head(sbuxRet, n=3)

# CC returns using Return.calculate()
sbuxRetC = Return.calculate(sbuxMonthlyPrices, method="log")
head(sbuxRetC, n=3)

```

## Plot Simple Returns

```{r}
# use default line style
plot.zoo(sbuxRet, main="SBUX Simple Monthly Return", 
         lwd=2, col="blue", ylab="Return")
abline(h=0)

```

## Plot Simple Returns

```{r}
# use type="h" instead of default type="l"
plot.zoo(sbuxRet, main="SBUX Simple Monthly Return", 
         type="h", lwd=2, col="blue", ylab="Return")
abline(h=0)

```

## Compare Simple and CC Returns

```{r}
# plot simple and cc returns on same graph
dataToPlot = merge(sbuxRet, sbuxRetC)
colnames(dataToPlot) = c("Simple", "CC")
plot.zoo(dataToPlot, main="Simple vs CC Returns", plot.type="single", 
         ylab="Returns", lwd=2, col=c("black", "red"))
abline(h=0)
legend("bottomleft", legend=colnames(dataToPlot),
       lty="solid", lwd=2, col=c("black", "red"))
```

## Compare Simple and CC Returns

```{r}
# plot simple and cc returns in different panels
my.panel <- function(...) {
  lines(...)
  abline(h=0)
}
plot.zoo(dataToPlot, main="Simple vs CC Returns", plot.type="multiple", 
         panel=my.panel, lwd=2, col=c("black", "red"))
```

## Dynamic (Interactive) Plots using dygraphs

Use the R package dygraphs to create dynamic time series graphs that can be viewed in a web browser. See https://rstudio.github.io/dygraphs/. 

```{r}
# basic time series plot - use the mouse to move about the plot
dygraph(sbuxMonthlyPrices) 
```

## Dynamic (Interactive) Plots using dygraphs

```{r}
# basic time series plot with range slider underneath
dygraph(sbuxMonthlyPrices) %>% dyRangeSelector()

```