Answer To: Project 2 – Portfolio Returns Step 1: Take the programs from Regenstein Chapters 2 and 3, and create...
Sanchi answered on Mar 01 2021
AS21/.RDataAS21/.RData
AS21/.Rhistorylibrary(quantmod)
#
# Package quantmod helps us to retrieve data from various sources, in this case, Yahoo! Finance.
# Also note that it calls the package xts.
#
library(purrr)
#
# As a side note, package purrr is part of the tidyverse. We use it here for convenience.
#
#
# The following packages are used in the xts universe.
# Package PerformanceAnalytics performs several useful calculations.
# Package highcharter is actually a "wrapper" function for the Javascript 'Highcharts' library,
# including shortcut functions to plot R objects. 'Highcharts'
# offers numerous chart types with a simple configuration syntax.
#
library(PerformanceAnalytics)
#
# As a side note, package purrr is part of the tidyverse. We use it here for convenience.
#
#
# The following packages are used in the xts universe.
# Package PerformanceAnalytics performs several useful calculations.
# Package highcharter is actually a "wrapper" function for the Javascript 'Highcharts' library,
# including shortcut functions to plot R objects. 'Highcharts'
# offers numerous chart types with a simple configuration syntax.
install.packages("PerformanceAnalytics")
library(PerformanceAnalytics)
library(highcharter)
install.packages("highcharter")
library(highcharter)
#
# Select stocks (ETFs)
# SPY: State Street S&P 500 Index ETF
# EFA: iShares Non-U.S. Equity Index ETF
# IJS: iShares S&P Small-Cap 600 Value ETF
# EEM: iShares MSCI Emerging Markets Index ETF
# AGG: iShares BBG Barclays U.S. Aggregate Index Bond ETF
#
symbols <- c("SPY", "EFA", "IJS", "EEM", "AGG")
# We use the map function from package purrr to apply Ad(get(.)) to the imported prices.
# The map function is an elegant, easily understandable way to do looping (e.g., for loop).
# The call to Ad(get(.)) gets the split and dividend adjusted prices for each security.
# The result is the daily price series' for each security.
# Since we would like the data in a single xts object, we will use the reduce(merge) command.
# The reduce(merge) combines the 5 lists into a single xts object.
# We also add the variable names, which correspond to the names of the individual securities.
# Also note that we are piping (%>%) commands together. You can think of %<% as, "and now then
# we do this....
#
prices <-
getSymbols(symbols,
src = 'yahoo',
from = "2012-12-31",
to = "2017-12-31",
auto.assign = TRUE,
warnings = FALSE) %>%
map(~Ad(get(.))) %>%
reduce(merge) %>%
`colnames<-` (symbols)
View(AGG)
View(prices)
prices_monthly <- to.monthly(prices,
indexAt = "lastof",
OHLC = FALSE)
View(prices_monthly)
View(prices_monthly)
#
# Head is a convenient function to print out the first few lines of a file. It's in base R,
# but an improved version is contained in the tidyverse function dplyr.
#
head(prices_monthly)
asset_returns_xts <-
Return.calculate(prices_monthly,
method = "log") %>%
na.omit()
head(asset_returns_xts)
highchart(type = "stock") %>%
hc_title(text = "Monthly Log Returns") %>%
hc_add_series(asset_returns_xts[, symbols[1]],
name = symbols[1]) %>%
hc_add_series(asset_returns_xts[, symbols[2]],
name = symbols[2]) %>%
hc_add_series(asset_returns_xts[, symbols[3]],
name = symbols[3]) %>%
hc_add_series(asset_returns_xts[, symbols[4]],
name = symbols[4]) %>%
hc_add_series(asset_returns_xts[, symbols[5]],
name = symbols[5]) %>%
hc_add_theme(hc_theme_flat()) %>%
hc_navigator(enabled = FALSE) %>%
hc_scrollbar(enabled = FALSE) %>%
hc_exporting(enabled = TRUE) %>%
hc_legend(enabled = TRUE)
hc_hist_fun <- function(n = 1, object, color) {
hc_hist <- hist(object[, symbols[n]],
breaks = 50,
plot = FALSE)
hchart(hc_hist, color = color) %>%
hc_title(text =
paste(symbols[n],
"Log Returns Distribution",
sep = " ")) %>%
hc_add_theme(hc_theme_flat()) %>%
hc_exporting(enabled = TRUE) %>%
hc_legend(enabled = FALSE)
}
hc_hist_fun(1, asset_returns_xts, "cornflowerblue")
hc_hist_fun(2, asset_returns_xts, "green")
hc_hist_fun(3, asset_returns_xts, "pink")
hc_hist_fun(4, asset_returns_xts, "purple")
hc_hist_fun(5, asset_returns_xts, "yellow")
# Weights
w <- c(0.25, 0.25, 0.20, 0.20, 0.10)
portfolio_returns_xts_rebalanced_monthly <-
Return.portfolio(asset_returns_xts,
weights = w,
rebalance_on = "months") %>%
`colnames<-`("returns")
head(portfolio_returns_xts_rebalanced_monthly)
highchart(type = "stock") %>%
hc_title(text = "Portfolio Monthly Returns") %>%
hc_add_series(portfolio_returns_xts_rebalanced_monthly$returns,
name = "Rebalanced Monthly",
color = "cornflowerblue") %>%
hc_add_theme(hc_theme_flat()) %>%
hc_navigator(enabled = FALSE) %>%
hc_scrollbar(enabled = FALSE) %>%
hc_legend(enabled = TRUE) %>%
hc_exporting(enabled = TRUE)
hc_portfolio <-
hist(portfolio_returns_xts_rebalanced_monthly$returns,
breaks = 50,
plot = FALSE)
hchart(hc_portfolio,
color = "cornflowerblue",
name = "Portfolio") %>%
hc_title(text = "Monthly Returns Distribution") %>%
hc_add_theme(hc_theme_flat()) %>%
hc_exporting(enabled = TRUE)
---
title: "Returns Distribution"
runtime: shiny
output:
flexdashboard::flex_dashboard:
orientation: rows
source_code: embed
---
library(tidyverse)
library('tidyverse')
library(highcharter)
library('tidyverse')
library(highcharter)
library(tidyquant)
install.packages("tidyquant")
install.packages("tidyquant")
library(tidyquant)
library(timetk)
fluidRow(
column(6,
textInput("stock1", "Stock 1", "SPY")),
column(5,
numericInput("w1", "Portf. %", 25, min = 1, max = 100))
)
fluidRow(
column(6,
textInput("stock2", "Stock 2", "EFA")),
column(5,
numericInput("w2", "Portf. %", 25, min = 1, max = 100))
)
fluidRow(
column(6,
textInput("stock3", "Stock 3", "IJS")),
column(5,
numericInput("w3", "Portf. %", 20, min = 1, max = 100))
)
fluidRow(
column(6,
textInput("stock4", "Stock 4", "EEM")),
column(5,
numericInput("w4", "Portf. %", 20, min = 1, max = 100))
)
fluidRow(
column(6,
textInput("stock5", "Stock 5", "AGG")),
column(5,
numericInput("w5", "Portf. %", 10, min = 1, max = 100))
)
fluidRow(
column(7,
dateInput("date", "Starting Date", "2013-01-01", format = "yyyy-mm-dd"))
)
fluidRow(
column(7,
selectInput("rebalance", "rebalance freq",
c("Yearly" = "years",
"Monthly" = "months",
"Weekly" = "weeks"))
)
)
actionButton("go", "Submit")
portfolio_returns_byhand <- eventReactive(input$go, {
symbols <- c(input$stock1, input$stock2, input$stock3, input$stock4, input$stock5)
prices <- getSymbols(symbols, src = 'yahoo', from = input$date,
auto.assign = TRUE, warnings = FALSE) %>%
map(~Ad(get(.))) %>%
reduce(merge) %>%
`colnames<-`(symbols)
w <- c(input$w1/100, input$w2/100,
input$w3/100, input$w4/100, input$w5/100)
asset_returns_long <-
prices %>%
to.monthly(indexAt = "last", OHLC = FALSE) %>%
tk_tbl(preserve_index = TRUE, rename_index = "date") %>%
gather(asset, returns, -date) %>%
group_by(asset) %>%
mutate(returns = (log(returns) - log(lag(returns))))
portfolio_returns_byhand <-
asset_returns_long %>%
tq_portfolio(assets_col = asset,
returns_col = returns,
weights = w,
col_rename = "returns")
})
library('tidyverse')
library(highcharter)
install.packages("tidyquant")
library(tidyquant)
library(timetk)
fluidRow(
column(6,
textInput("stock1", "Stock 1", "SPY")),
column(5,
numericInput("w1", "Portf. %", 25, min = 1, max = 100))
)
devtools::install_github("shiny", "rstudio")
install.packages("shiny")
library(shiny)```
library("shiny")```
library(shiny)
library('tidyverse')
library(highcharter)
install.packages("tidyquant")
library(tidyquant)
library(timetk)
install.packages("shiny")
library(shiny)
fluidRow(
column(6,
textInput("stock1", "Stock 1", "SPY")),
column(5,
numericInput("w1", "Portf. %", 25, min = 1, max = 100))
)
fluidRow(
column(6,
textInput("stock2", "Stock 2", "EFA")),
column(5,
numericInput("w2", "Portf. %", 25, min = 1, max = 100))
)
fluidRow(
column(6,
textInput("stock3", "Stock 3", "IJS")),
column(5,
numericInput("w3", "Portf. %", 20, min = 1, max = 100))
)
fluidRow(
column(6,
textInput("stock4", "Stock 4", "EEM")),
column(5,
numericInput("w4", "Portf. %", 20, min = 1, max = 100))
)
fluidRow(
column(6,
textInput("stock5", "Stock 5", "AGG")),
column(5,
numericInput("w5", "Portf. %", 10, min = 1, max = 100))
)
fluidRow(
column(7,
dateInput("date", "Starting Date", "2013-01-01", format = "yyyy-mm-dd"))
)
fluidRow(
column(7,
selectInput("rebalance", "rebalance freq",
c("Yearly" = "years",
"Monthly" = "months",
"Weekly" = "weeks"))
)
)
actionButton("go", "Submit")
portfolio_returns_byhand <- eventReactive(input$go, {
symbols <- c(input$stock1, input$stock2, input$stock3, input$stock4, input$stock5)
prices <- getSymbols(symbols, src = 'yahoo', from = input$date,
auto.assign = TRUE, warnings = FALSE) %>%
map(~Ad(get(.))) %>%
reduce(merge) %>%
`colnames<-`(symbols)
w <- c(input$w1/100, input$w2/100,
input$w3/100, input$w4/100, input$w5/100)
asset_returns_long <-
prices %>%
to.monthly(indexAt = "last", OHLC = FALSE) %>%
tk_tbl(preserve_index = TRUE, rename_index = "date") %>%
gather(asset, returns, -date) %>%
group_by(asset) %>%
mutate(returns = (log(returns) - log(lag(returns))))
portfolio_returns_byhand <-
asset_returns_long %>%
tq_portfolio(assets_col = asset,
returns_col = returns,
weights = w,
col_rename = "returns")
})
renderPlot({
portfolio_returns_byhand() %>%
ggplot(aes(x = returns)) +
geom_histogram(alpha = 0.25, binwidth = .01, fill = "cornflowerblue")
})
renderPlot({
portfolio_returns_byhand() %>%
ggplot(aes(x = returns)) +
geom_histogram(alpha = 0.25, binwidth = .01, fill = "cornflowerblue")
})
renderPlot({
portfolio_returns_byhand() %>%
ggplot(aes(x = returns)) +
geom_density(size = 1, color = "red")
})
renderPlot({
portfolio_returns_byhand() %>%
ggplot(aes(x = returns)) +
geom_histogram(alpha = 0.25, binwidth = .01, fill = "cornflowerblue") +
geom_density(geom = "line", size = 1, color = "red")
})
portfolio_returns_byhand() %>%
ggplot(aes(x = returns)) +
geom_histogram(alpha = 0.25, binwidth = .01, fill = "cornflowerblue") +
geom_density(geom = "line", size = 1, color = "red")
renderPlot({
portfolio_returns_byhand() %>%
ggplot(aes(x = returns)) +
geom_histogram(alpha = 0.25, binwidth = .01, fill = "cornflowerblue") +
geom_density(geom = "line", size = 1, color = "red")
})
renderPlot({
portfolio_returns_byhand() %>%
ggplot(aes(x = returns)) +
geom_histogram(alpha = 0.25, binwidth = .01, fill = "cornflowerblue") +
geom_density(geom = "line", size = 1, color = "red")
})
```{r}
AS21/Step1.r# Return calculations in xts
# December 11, 2019
library(quantmod)
#
# Package quantmod helps us to retrieve data from various sources, in this case, Yahoo! Finance.
# Also note that it calls the package xts.
#
library(purrr)
#
# As a side note, package purrr is part of the tidyverse. We use it here for convenience.
#
#
# The following packages are used in the xts universe.
# Package PerformanceAnalytics performs several useful calculations.
# Package highcharter is actually a "wrapper" function for the Javascript 'Highcharts' library,
# including shortcut functions to plot R objects. 'Highcharts'
# offers numerous chart types with a simple configuration syntax.
#install.packages("PerformanceAnalytics")
library(PerformanceAnalytics)
#install.packages("highcharter")
library(highcharter)
#
# Select stocks (ETFs)
# SPY: State Street S&P 500 Index ETF
# EFA: iShares Non-U.S. Equity Index ETF
# IJS: iShares S&P Small-Cap 600 Value ETF
# EEM: iShares MSCI Emerging Markets Index ETF
# AGG: iShares BBG Barclays U.S. Aggregate Index Bond ETF
#
symbols <- c("Open", "High", "Low", "Close", "Adj.Close","Volume")
#
# The function "getSymbols" which follows, is part of the quantmod package that allows you to retrieve data
# from various different data sources, in...