{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE, message = FALSE)

Coding basics

R as a calculator

{r} 1000/10 x <- 1000/10 #x ## assignment symbol

What’s in a name?

Calling functions

Use of TAB

{r} seq(from=1,to=10,by=1)

continuation character, +

{r} seq(from=1,to=10)

Printing to screen

{r} y<- seq(from=1,to=10) y {r} #Load Packages library(tidyverse) library(tidyquant)

##Stock Index

tq_get

Stocks by Yahoo Finance

{r} stock <- tq_get("TSLA")

Economic data from FRED

{r} unemployment_nh <- tq_get("NHUR", get= "economic.data") unemployment_nh

{r} #Load Packages library(tidyverse) library(tidyquant) #Import Data AAPL <- tq_get("AAPL")

Line Chart

{r} AAPL %>% ggplot(aes(x = date, y = close)) + geom_line() + labs(title = "AAPL Line Chart", y = "Closing Price", x = "") + theme_tq()

#Bar Chart {r} AAPL %>% tail(30) %>% ggplot(aes(x = date, y = close)) + geom_barchart(aes(open = open, high = high, low = low, close = close)) + labs(title = "AAPL Bar Chart", y = "Closing Price", x = "") + theme_tq() # Candelstick Chart {r} AAPL %>% tail(30) %>% ggplot(aes(x = date, y = close)) + geom_candlestick(aes(open = open, high = high, low = low, close = close)) + labs(title = "AAPL Candlestick Chart", y = "Closing Price", x = "") + theme_tq()

{r} #Load Packages library(tidyverse) library(tidyquant)

{r} Ra <- c("AAPL", "GOOG", "NFLX") %>% tq_get(get = "stock.prices", from = "2010-01-01", to = "2015-12-31") %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = "monthly", col_rename = "Ra") Ra ## 2 Get Baseline and Convert to returns {r} Rb <- "XLK" %>% tq_get(get = "stock.prices", from = "2010-01-01", to = "2015-12-31") %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = "monthly", col_rename = "Rb") Rb

Join the Two Tables

{r} RaRb <- left_join(Ra, Rb, by = c("date" = "date")) RaRb ##Calculate CAPM {r} RaRb_capm <- RaRb %>% tq_performance(Ra = 9, Rb = Rb, performance_fun = table.CAPM) RaRb_capm

{r} RaRb_skewness <- RaRb %>% tq_performance(Ra = Ra, Rb = NULL, performance_fun = skewness) RaRb_skewness Ra <- c("AAPL", "GOOG", "NFLX") %>% group_by(symbol) %>% tq_transmute(adjusted, periodReturn, period = "monthly", col_rename = "Ra")