#' Lagged Correlations function
#'
#' Calculate correlation beetwen two numeric vector x and y for lagged values of x. Both vectors need to have equal length.
#' @param x Numeric vector of asset prices or returns (to be lagged)
#' @param y Numeric vector of asset prices or returns
#' @param max_lag Max number of lags for vector x. Default set to lengt(x) - 2
#' @param plot If TRUE plot correlation for each lag
#'
#' @return Numeric vector of correlations for different time lags.
#' @export
#'
#' @examples
#' tickers <- c('wig20', 'mwig40')
#' sapply(tickers
#' ,stooq_download
#' ,destination = 'datasets\\')
#' files <- list.files('datasets\\')
#' close_prices <- df_prices(files = files
#' ,source = 'datasets\\')
#' x <- close_prices[,2] %>%
#' unlist()
#' y <- close_prices[,3] %>%
#' unlist()
#' lagged_correlations(x, y, max_lag = 200)
lagged_correlations <- function(x
,y
,max_lag = length(x) - 2
,plot = TRUE){
if (class(x) != 'numeric'){
stop('x is not numeric vector')
}
if (class(y) != 'numeric'){
stop('y is not numeric vector')
}
if (length(x) != length(y)){
stop('lengths of x and y differ')
}
rho <- c()
rho[1] <- cor(x, y)
for (i in 1:max_lag) {
rho[i+1] <- cor(
as.numeric(
na.omit(dplyr::lag(x, i))
)
,y[-(1:i)]
)
}
if (plot == TRUE){
plot(1:length(rho)
,rho
,type = 'l'
,lwd = 1.5
,xlab = 'Lag'
,ylab = 'Correlation')
}
return(rho)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.