Project 2 – Portfolio Returns Step 1: Take the programs from Regenstein Chapters 2 and 3, and create your own portfolio. Graph asset and portfolio returns. Apply the shiny app. Try modifying the start...

1 answer below »
hello I need help with this finance assignment that is coding in R programming language


Project 2 – Portfolio Returns Step 1: Take the programs from Regenstein Chapters 2 and 3, and create your own portfolio. Graph asset and portfolio returns. Apply the shiny app. Try modifying the start and end dates of your data and repeat the process. Step 2: Calculate and graph the rolling standard deviation of your portfolio. Repeat using different rolling windows and start/end dates. Apply the shiny app. Step 3: Use the rolling skewness and kurtosis shiny app to analyze your portfolio. Does your portfolio follow a normal distribution? Step 4: Write a short summary of your analysis in Microsoft Word, and incorporate graphs using the snipping tool. 2 Returns in XTS Returns in XTS and Tidyverse The Process Call libraries Quantmod – retrieves data from various sources Purrr – used for iteration PerformanceAnalytics – performs statistics, used frequently with xts Highcharter – a “wrapper” package for the Highcharts Javascript library Select securities (ETFs in our examples) SPY: State Street S&P 500 Index ETF EFA: iShares Non-U.S. Equity Index ETF IJS: iShares S&P Small-Cap 600 Index ETF EEM: iShares MSCI Emerging Markets Index ETF AGG: iShares BBG Barclays U.S. Aggregate Index Bond ETF Retrieving Data from Yahoo! Finance Load daily price data from Yahoo! Finance into xts object “price” getSymbols – from package quantmod, retrieves data from various sources symbols – vector of stock symbols src – from Yahoo! Finance (other data sources are available – see documentation) from =, to = - select dates auto.assign = TRUE – assigns an R-legal name from the ticker symbol map(~Ad(get(.))) – from package purrr, applies a function to each element of a vector (an elegant for loop). Keeping only the adjusted prices for each ticker (vector). reduce(merge) – merges the five price vectors into a single xts object `colnames<-` (symbols) – labels the variables in the xts object load end-of-month prices into object “prices_monthly” to.monthly – a zoo package function; zoo is called by xts convert monthly prices into log returns and load into “asset_returns_xts” return.calculate – from the performanceanalytics package plotting security and portfolio returns plot returns using highchart write a function hc_hist_fun to create histograms for each security hc_hist – calls the base function “hist” on the data, including breaks call hchart on the resulting object call hc_hist_fun for each security create weighted portfolio returns in xts load vector of weights return.portfolio – from the performanceanalytics package plot portfolio returns using highchart (linechart) plot portfolio returns using hchart using same logic as in function hc_hist_fun for help with parameters and calls – google on [“package” in r] security returns in tidyverse data acquisition is the same, except we use call libraries quantmod and tidyverse (purrr is one of the tidyverse packages) we convert daily to monthly prices in asset_returns_dplyr_byhand begin with xts object “prices”, use the pipe to execute to.monthly() convert the xts date index to a variable with data.frame() we then remove the row names (dates) because tibbles do not contain row names use gather() to tidy the xts object – we demonstrate by printing use group_by(asset) and create returns using mutate (which is looking for tidy data) select only the date, asset, and returns variable (no prices) spread() to untidy the dataset, then select the variables for the date and returns for each of the symbols take asset_returns_dplyr_byhand and delete the first row (all nas) plotting using the ggplot() package (tidy) tidy the data so we can use ggplot() in asset_returns_long take asset_returns_dplyr_byhand and gather() the data to tidy it, grouping by asset use asset_returns_long as input into ggplot() for several plots create a vector of portfolio weights and convert to a tibble create portfolio_returns_dplyr_byhand start with asset_returns_long (our tidy dataset) group_by(asset) use mutate to associate each weight with its respective asset and calculate the weighted returns group_by(date) so we can use summarize() create the weighted average return for each date use portfolio_returns_dplyr_byhand (a tidy dataset) to create plots in ggplot() package ggplot() (continued) use ggplot() to create a scatterplot and a histogram create a compound histogram: get asset_returns_long and use geom_historgram and fill = asset to “stack” individual security returns use portfolio_dplyr_byhand to superimpose the portfolio histogram on top of the asset return histogram create a histogram and density function superimposed for the portfolio in tidyquant similar to tidyverse, except: create asset_returns_tq_builtin instead of asset_returns_dplyr_byhand uses tk_tbl() from package timetk and tqtransmute() from package tidyquant create portfolio_returns_tq_rebalanced_monthly instead of portfolio_returns_dplyr_byhand uses tq_portfolio() from tidyquant recent developments package timetk() is a new package for time series analysis in r that is tidy oriented and contains significant improvements over tidyquant and other package. package tibbletime() has been deprecated (no longer supported and not recommended for use). package tidymodels() has collected tidy packages, similar to tidyverse() to provide a “one-stop” source for a variety of analysis packages. tidymodels is designed for (among other things) machine learning projects i am updating my code as i have time to reflect these new innovations. trade-off: do i develop new material, or do i update my current programs first? (symbols)="" –="" labels="" the="" variables="" in="" the="" xts="" object="" load="" end-of-month="" prices="" into="" object="" “prices_monthly”="" to.monthly="" –="" a="" zoo="" package="" function;="" zoo="" is="" called="" by="" xts="" convert="" monthly="" prices="" into="" log="" returns="" and="" load="" into="" “asset_returns_xts”="" return.calculate="" –="" from="" the="" performanceanalytics="" package="" plotting="" security="" and="" portfolio="" returns="" plot="" returns="" using="" highchart="" write="" a="" function="" hc_hist_fun="" to="" create="" histograms="" for="" each="" security="" hc_hist="" –="" calls="" the="" base="" function="" “hist”="" on="" the="" data,="" including="" breaks="" call="" hchart="" on="" the="" resulting="" object="" call="" hc_hist_fun="" for="" each="" security="" create="" weighted="" portfolio="" returns="" in="" xts="" load="" vector="" of="" weights="" return.portfolio="" –="" from="" the="" performanceanalytics="" package="" plot="" portfolio="" returns="" using="" highchart="" (linechart)="" plot="" portfolio="" returns="" using="" hchart="" using="" same="" logic="" as="" in="" function="" hc_hist_fun="" for="" help="" with="" parameters="" and="" calls="" –="" google="" on="" [“package”="" in="" r]="" security="" returns="" in="" tidyverse="" data="" acquisition="" is="" the="" same,="" except="" we="" use="" call="" libraries="" quantmod="" and="" tidyverse="" (purrr="" is="" one="" of="" the="" tidyverse="" packages)="" we="" convert="" daily="" to="" monthly="" prices="" in="" asset_returns_dplyr_byhand="" begin="" with="" xts="" object="" “prices”,="" use="" the="" pipe="" to="" execute="" to.monthly()="" convert="" the="" xts="" date="" index="" to="" a="" variable="" with="" data.frame()="" we="" then="" remove="" the="" row="" names="" (dates)="" because="" tibbles="" do="" not="" contain="" row="" names="" use="" gather()="" to="" tidy="" the="" xts="" object="" –="" we="" demonstrate="" by="" printing="" use="" group_by(asset)="" and="" create="" returns="" using="" mutate="" (which="" is="" looking="" for="" tidy="" data)="" select="" only="" the="" date,="" asset,="" and="" returns="" variable="" (no="" prices)="" spread()="" to="" untidy="" the="" dataset,="" then="" select="" the="" variables="" for="" the="" date="" and="" returns="" for="" each="" of="" the="" symbols="" take="" asset_returns_dplyr_byhand="" and="" delete="" the="" first="" row="" (all="" nas)="" plotting="" using="" the="" ggplot()="" package="" (tidy)="" tidy="" the="" data="" so="" we="" can="" use="" ggplot()="" in="" asset_returns_long="" take="" asset_returns_dplyr_byhand="" and="" gather()="" the="" data="" to="" tidy="" it,="" grouping="" by="" asset="" use="" asset_returns_long="" as="" input="" into="" ggplot()="" for="" several="" plots="" create="" a="" vector="" of="" portfolio="" weights="" and="" convert="" to="" a="" tibble="" create="" portfolio_returns_dplyr_byhand="" start="" with="" asset_returns_long="" (our="" tidy="" dataset)="" group_by(asset)="" use="" mutate="" to="" associate="" each="" weight="" with="" its="" respective="" asset="" and="" calculate="" the="" weighted="" returns="" group_by(date)="" so="" we="" can="" use="" summarize()="" create="" the="" weighted="" average="" return="" for="" each="" date="" use="" portfolio_returns_dplyr_byhand="" (a="" tidy="" dataset)="" to="" create="" plots="" in="" ggplot()="" package="" ggplot()="" (continued)="" use="" ggplot()="" to="" create="" a="" scatterplot="" and="" a="" histogram="" create="" a="" compound="" histogram:="" get="" asset_returns_long="" and="" use="" geom_historgram="" and="" fill="asset" to="" “stack”="" individual="" security="" returns="" use="" portfolio_dplyr_byhand="" to="" superimpose="" the="" portfolio="" histogram="" on="" top="" of="" the="" asset="" return="" histogram="" create="" a="" histogram="" and="" density="" function="" superimposed="" for="" the="" portfolio="" in="" tidyquant="" similar="" to="" tidyverse,="" except:="" create="" asset_returns_tq_builtin="" instead="" of="" asset_returns_dplyr_byhand="" uses="" tk_tbl()="" from="" package="" timetk="" and="" tqtransmute()="" from="" package="" tidyquant="" create="" portfolio_returns_tq_rebalanced_monthly="" instead="" of="" portfolio_returns_dplyr_byhand="" uses="" tq_portfolio()="" from="" tidyquant="" recent="" developments="" package="" timetk()="" is="" a="" new="" package="" for="" time="" series="" analysis="" in="" r="" that="" is="" tidy="" oriented="" and="" contains="" significant="" improvements="" over="" tidyquant="" and="" other="" package.="" package="" tibbletime()="" has="" been="" deprecated="" (no="" longer="" supported="" and="" not="" recommended="" for="" use).="" package="" tidymodels()="" has="" collected="" tidy="" packages,="" similar="" to="" tidyverse()="" to="" provide="" a="" “one-stop”="" source="" for="" a="" variety="" of="" analysis="" packages.="" tidymodels="" is="" designed="" for="" (among="" other="" things)="" machine="" learning="" projects="" i="" am="" updating="" my="" code="" as="" i="" have="" time="" to="" reflect="" these="" new="" innovations.="" trade-off:="" do="" i="" develop="" new="" material,="" or="" do="" i="" update="" my="" current="" programs="">
Answered 4 days AfterFeb 25, 2021

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
151 Votes
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 config
uration 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...
SOLUTION.PDF

Answer To This Question Is Available To Download

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here