02/05/2017

How to calculate correlation coefficients for US stock sectors

Click and see the complete code


#required

library(dplyr)
library(quantmod)
library(dygraphs)


#get etf data from http://www.sectorspdr.com/sectorspdr/ 

tickers<- c="" p="">sectorNames <- c="" discretionary="" nbsp="" onsumer="" p="" staples="">                 "Energy", "Financials", "Health Care", "Industrials",
                 "Materials", "Information Technology", "Utilities", "Index")
etf_ticker_sectors <- data_frame="" p="" sectornames="" tickers="">
#check data
etf_ticker_sectors

# # A tibble: 10 × 2
# tickers            sectorNames
#                  
#   1      XLY Consumer Discretionary
# 2      XLP       Consumer Staples
# 3      XLE                 Energy
# 4      XLF             Financials
# 5      XLV            Health Care
# 6      XLI            Industrials
# 7      XLB              Materials
# 8      XLK Information Technology
# 9      XLU              Utilities
# 10     SPY                  Index


#calculate weekly return

sector_weekly_returns <- function="" p="" tickers="">
#download data
  symbols <- auto.assign="TRUE," getsymbols="" tickers="" warnings="FALSE)</p">
#get only close price
  prices <- cl="" do.call="" function="" get="" lapply="" merge="" p="" symbols="" x="">
#calculate weekly log-based return using a function, periodReturn()
  weekly_returns <- do.call="" lapply="" merge="" nbsp="" p="" prices="">                                          function(x) periodReturn(x, period = 'weekly', type = 'log')))


#Change the column names to the sector names from our dataframe above.

  colnames(weekly_returns) <- div="" etf_ticker_sectors="" sectornames="">
  return(weekly_returns)

}

weekly_returns = sector_weekly_returns(tickers)

weekly_returns
# 2008-10-10 -0.2205639196
# 2008-10-17  0.0518524493
# 2008-10-24 -0.0684872067
# 2008-10-31  0.1065890897
# 2008-11-07 -0.0311525633
# 2008-11-14 -0.0802735506
# 2008-11-21 -0.0855222458
# 2008-11-28  0.1248006016



#get rolling correlation between sector etf and s&p 500 etf

sector_index_correlation <- function="" p="" window="" x="">
#merge return of sector  and s&p500
  merged_xts <- merge="" ndex="" p="" weekly_returns="" x="">
#calculate rolling correlations using rollapply()
#pairwise.complete.obs automatically removes NA

  merged_xts$rolling_cor <- merged_xts="" nbsp="" p="" rollapply="" window="">                                      function(x) cor(x[,1], x[,2], use = "pairwise.complete.obs"),
                                      by.column = FALSE)

  names(merged_xts) <- c="" correlation="" ector="" p="" returns="">
  return(merged_xts)
}

#use a created function we made above

IT_SPY_correlation <- p="" sector_index_correlation="">  weekly_returns$'Information Technology', 26)

#draw graph using Dygragh

dygraph(IT_SPY_correlation$'Sector/SPY Correlation', main = "Correlation between SP500 and Tech ETF") %>%
  dyAxis("y", label = "Correlation") %>%
  dyRangeSelector(height = 20) %>%
  # Add shading for the recessionary period
  dyShading(from = "2007-12-01", to = "2009-06-01", color = "#FFE6E6") %>%
  # Add an event for the financial crisis.
  dyEvent(x = "2008-09-15", label = "Fin Crisis", labelLoc = "top", color = "red")






-reference-
http://blog.naver.com/htk1019/220966797230

Share this

Tag :

0 Comment to "How to calculate correlation coefficients for US stock sectors"

Post a Comment