#install.packages("tibbletime")
library(tidyverse)
library(tidyquant)
library(timetk)
library(tibbletime)
library(viridis)
library(highcharter)
library(ggthemes)
library(dygraphs)
library(knitr)
Facebook,Amazon,Apple, Microsoft,google and Tesla are among the some of the most treaured,valued and highly priced srocks in the stock market today. We would to like to compare the returns on these stocks since June 2012. Facebook listed in May 2012.These tech company dominate in their respective areas of online marketing,social media,computer software, automotive and pc’s. A large number of rhe Amazon data is missing.
# The symbols vector holds our tickers.
tickers <- c("FB", "AAPL", "MSFT","GOOGL","TSLA","AMZ")
# The prices object will hold our raw price data throughout this book.
prices <-
getSymbols(tickers, src = 'yahoo', from = "2012-06-01",
auto.assign = TRUE, warnings = FALSE)
prices
[1] "FB" "AAPL" "MSFT" "GOOGL" "TSLA" "AMZ"
We convert Facebook’s daily prices to monthly with help of timekt and tidyquant packages. tk_bl() converts the data from xts to tidy dataframe frame format and the tidyquant allows us to compute the returns on the monthly adjusted prices.
prices[1]%>%get()%>%tk_tbl()%>%
tq_transmute(select = FB.Adjusted,
mutate_fun = periodReturn,
period = "monthly",
type = "arithmetic")%>%head()
We can obtain the adjusted prices for each stock by the Ad functioon combined with get function with the help of lapply and do.call which allows a function to be passed over list data.
AdjustedPrices <- do.call(merge, lapply(tickers, function(x) Ad(get(x))))
AdjustedPrices%>%head()%>%tk_tbl()
Lets visualize these adjusted prices with the dygraph package
dateWindow <- c("2016-06-01", "2017-09-29")
dygraph(AdjustedPrices, main = "Value", group = "stock") %>%
dyRebase(value = 100) %>%
dyRangeSelector(dateWindow = dateWindow)
Lets visualize these adjusted prices with the highchart package
hc <- highchart(type = "stock") %>%
hc_title(text = "Charting some Stocks") %>%
hc_subtitle(text = "Data extracted using quantmod package") %>%
hc_add_series(AdjustedPrices$FB.Adjusted, name=names(AdjustedPrices$FB.Adjusted)) %>%
hc_add_series(AdjustedPrices$MSFT.Adjusted, name=names(AdjustedPrices$MSFT.Adjusted)) %>%
hc_add_series(AdjustedPrices$GOOGL.Adjusted, name=names(AdjustedPrices$GOOGL.Adjusted)) %>%
hc_add_series(AdjustedPrices$TSLA.Adjusted, name=names(AdjustedPrices$TSLA.Adjusted)) %>%
hc_add_series(AdjustedPrices$AMZ.Adjusted, name=names(AdjustedPrices$AMZ.Adjusted)) %>%
hc_add_series(AdjustedPrices$AAPL.Adjusted, name=names(AdjustedPrices$AAPL.Adjusted))%>%
hc_add_theme(hc_theme_flat())
#hc_add_theme(hc_theme_economist())
hc
Monthly log of returns on assets.We find the monthly log of returns with the periodReturn function in the tidyquant package.
colnames<-c("date","AAPL", "AMZ", "FB","GOOGL","MSFT","TSLA")
monthly_returns <- AdjustedPrices %>%
tk_tbl(preserve_index = TRUE, rename_index = "date") %>%
gather(asset, prices, -date)%>%
group_by(asset) %>%
tq_transmute(mutate_fun = periodReturn, period = "monthly", type = "log") %>%
spread(asset, monthly.returns)%>%
`colnames<-`(colnames )
monthly_returns%>%head()
We can also find the yearly return on Facebook’s adjusted stock price as follows:
annual_returns<-prices[1]%>%get()%>%tk_tbl() %>%
tq_transmute(select = FB.Adjusted,
mutate_fun = periodReturn,
period = "yearly",
type = "arithmetic")
annual_returns%>%head()
# The symbols vector holds our tickers.
tickers <- c("FB", "AAPL", "MSFT","GOOGL","TSLA")
# The prices object will hold our raw price data throughout this book.
prices <-
getSymbols(tickers, src = 'yahoo', from = "2012-06-01",
auto.assign = TRUE, warnings = FALSE)
c=list()
for (i in 1:length(prices))
c[[i]]=prices[i]%>%get()%>%tk_tbl()%>%dplyr::select(noquote(paste(prices[i],"Adjusted",sep=".")))
c=as.data.frame.list(c)
index=prices[1]%>%get()%>%tk_tbl()%>%select(index)
index%>%head()
c=data.frame(index,c)
#colnames(c)<-c("date","FB", "AAPL","MSFT","GOOGL","TSLA")
c%>%head()
Another equivalent way of getting the adjusted prices is by the procedure below
# The symbols vector holds our tickers.
tickers <- c("FB", "AAPL", "MSFT","GOOGL","TSLA","AMZ")
# The prices object will hold our raw price data throughout this book.
prices <-
getSymbols(tickers, src = 'yahoo', from = "2012-06-01",
auto.assign = TRUE, warnings = FALSE) %>%
map(~Ad(get(.))) %>% #Extract (transformed) data from a suitable OHLC object. getSymbols('IBM',src='yahoo') Ad(IBM)
reduce(merge) %>% #reduce() combines from the left, reduce_right() combines from the right
`colnames<-`(tickers )
head(prices)%>%tk_tbl()
Convert daily prices to monthly prices using a call to to.monthly(prices, indexAt = “last”, OHLC = FALSE) from quantmod. The argument index = “last” tells the function whether we want to index to the first day of the month or the last day.
prices_monthly <- to.monthly(prices, indexAt = "last", OHLC = FALSE)
head(prices_monthly)%>%tk_tbl()
We now have an xts object, and we have moved from daily prices to monthly prices.
Return.calculate(prices_monthly, method = “log”) to convert to returns and save as an object called assed_returns_xts. Note this will give us log returns by the method = “log” argument. We could have used method = “discrete” to get simple returns.
#asset_returns_xts <- na.omit(Return.calculate(prices_monthly, method = "discreet"))
asset_returns_quantmod <- na.omit(CalculateReturns(prices_monthly, method = "log"))
head(asset_returns_quantmod)%>%tk_tbl()
We can also do the above calculations by hand with some help from the dplyr and timekt packages. The timekt can convert the xts object prices to a dataframe object which dplyr requires to work. We do the calculation by hand with the mutate function.
asset_returns_dplyr_byhand <- 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))))%>%
spread(asset, returns)%>%
select(date, tickers)
asset_returns_dplyr_byhand%>%head()
Instead of using to.monthlyand mutate, and then supplying our own calculation, we use tq_transmute(mutate_fun = periodReturn, period = “monthly”, type = “log”) and go straight from daily prices to monthly log returns. Note that we select the period as ‘monthly’ in that function call, which means we can pass in the raw daily prices xts object..
asset_returns_tq <- prices %>%
tk_tbl(preserve_index = TRUE, rename_index = "date") %>%
gather(asset, prices, -date) %>%
group_by(asset) %>%
tq_transmute(mutate_fun = periodReturn, period = "monthly", type = "log") %>%
spread(asset, monthly.returns) %>%
select(date, tickers)
asset_returns_tq%>%head()
With help of tibbletime package we can also approach this way. as_period converts the data from daily prices to monthly prices.
asset_returns_tbltime <- prices %>%
tk_tbl(preserve_index = TRUE, rename_index = "date") %>%
tbl_time(index = "date") %>%
as_period("monthly", side = "end") %>%
gather(asset, returns, -date) %>%
group_by(asset) %>%
tq_transmute(mutate_fun = periodReturn, type = "log") %>%
spread(asset, monthly.returns) %>%
select(date, tickers)
asset_returns_tbltime%>%head()
asset_returns_long <-
asset_returns_tq %>%
gather(asset, returns, -date)
head(asset_returns_long)
Let’s do the same with quantmod package.
tickers <- c("FB", "AAPL", "MSFT","GOOGL","TSLA","AMZ")
prices <-
getSymbols(tickers, src = 'yahoo', from = "2012-06-01",
auto.assign = TRUE, warnings = FALSE) %>%
map(~Ad(get(.))) %>%
reduce(merge) %>%
`colnames<-`(tickers)
# XTS method
prices_monthly <- to.monthly(prices, indexAt = "last", OHLC = FALSE)
asset_returns_quantmod <- na.omit(Return.calculate(prices_monthly, method = "log"))
asset_returns_quantmod%>%tk_tbl()%>%head()
# Tidyverse method, to long, tidy format
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))))
asset_returns_long%>%head()
We now have two objects holding monthly log returns: asset_returns_xts and asset_returns_long.
First, let’s use highcharter to visualize the xts formatted returns. Highcharter is fantastic for visualizing a time series or many time series. First, we set highchart(type = “stock”) to get a nice time series line. Then we add each of our series to the highcharter code flow. In this case, we’ll add our columns from the xts object.
highchart(type = "stock") %>%
hc_title(text = "Monthly log Returns") %>%
hc_add_series(asset_returns_quantmod$FB,
name = names(asset_returns_quantmod$FB)) %>%
hc_add_series(asset_returns_quantmod$AAPL,
name = names(asset_returns_quantmod$AAPL)) %>%
hc_add_series(asset_returns_quantmod$MSFT,
name = names(asset_returns_quantmod$MSFT)) %>%
hc_add_series(asset_returns_quantmod$GOOGL,
name = names(asset_returns_quantmod$GOOGL)) %>%
hc_add_series(asset_returns_quantmod$TSLA,
name = names(asset_returns_quantmod$TSLA))%>%
hc_add_series(asset_returns_quantmod$AMZ,
name = names(asset_returns_quantmod$AMZ))%>%
hc_add_theme(hc_theme_monokai())%>%
hc_navigator(enabled = TRUE) %>%
hc_scrollbar(enabled = TRUE)%>%
hc_yAxis(max = 8,min=-8)
Let’s remove the amazon stock returns from the list and see what happens to chart. There is a large number of missing data from the Amazon stock prices.
highchart(type = "stock") %>%
hc_title(text = "Monthly log Returns") %>%
hc_add_series(asset_returns_quantmod$FB,
name = names(asset_returns_quantmod$FB)) %>%
hc_add_series(asset_returns_quantmod$AAPL,
name = names(asset_returns_quantmod$AAPL)) %>%
hc_add_series(asset_returns_quantmod$MSFT,
name = names(asset_returns_quantmod$MSFT)) %>%
hc_add_series(asset_returns_quantmod$GOOGL,
name = names(asset_returns_quantmod$GOOGL)) %>%
hc_add_series(asset_returns_quantmod$TSLA,
name = names(asset_returns_quantmod$TSLA))
theme_set(theme_bw())
# Make so all titles centered in the upcoming ggplots
theme_update(plot.title = element_text(hjust = 0.5))
asset_returns_long %>%
ggplot(aes(x = returns, fill = asset)) +
geom_histogram(alpha = 0.25, binwidth = .01)+
scale_x_continuous(limits = c(-0.5, 0.5))+
scale_y_continuous(limits = c(0, 7))
Let’s use facet_wrap(~asset) to break these out by asset. We can add a title with ggtitle.
asset_returns_long %>%
ggplot(aes(x = returns, fill = asset)) +
geom_histogram(alpha = 0.25, binwidth = .01) +
facet_wrap(~asset) +
ggtitle("Monthly Returns Since 2012")+theme_bw()+
scale_x_continuous(limits = c(-0.5, 0.5))+
scale_y_continuous(limits = c(0, 7))
Maybe we don’t want to use a histogram, but instead want to use a density line to visualize the various distributions. We can use the stat_density(geom = “line”, alpha = 1) function to do this. The alpha argument is selecting a line thickness. Let’s also add a label to the x- and y-axis with the xlab and ylab functions.
asset_returns_long %>%
ggplot(aes(x = returns, colour = asset, fill = asset)) +
stat_density(geom = "line", alpha = 1) +
ggtitle("Monthly Returns Since 2012") +
xlab("monthly returns") +
ylab("distribution") +theme_bw()
That chart is quite readable, but we can also facet_wrap(~asset) to break the densities out into individual charts.
asset_returns_long %>%
ggplot(aes(x = returns, colour = asset, fill = asset)) +
stat_density(geom = "line", alpha = 1) +
geom_histogram(alpha = 0.25, binwidth = .01) +
facet_wrap(~asset) +
ggtitle("Monthly Returns Since 2012") +
xlab("monthly returns") +
ylab("distribution") +
scale_y_continuous(limits = c(0, 7))