R/returns_diagnostics.R

Defines functions returns_diagnostics

Documented in returns_diagnostics

#' Return Diagnostics function
#'
#' Download financial time series from https://stooq.pl/ in .csv format.
#' @param returns Numeric vector of asset returns
#' @param lags Number of lags for ACF plot and Ljung-box test. Default set to 10
#' @param significance Significance level for hypothesis testing. Deafult set to 0.05
#' @param plot If TRUE plot diagnostics plots (histogram with fitted densities, qq-plots, ACF)
#'
#' @return List of fitted normal and t-student parameters. Results of stationarity tests (Ljung-Box and ADF). Additionaly 2x2 plot is generated with histogram of returns and fitted densities, qq-plots and ACF function.
#' @export
#'
#' @examples
#' files <- list.files('datasets\\')
#' close_prices <- df_prices(files = files
#'                           ,source = 'datasets\\')
#' weights <- c(0.40, 0.40, 0.20)
#' portfolio_returns(close_prices, weights) %>%
#'  returns_diagnostics()

returns_diagnostics <- function(returns
                                ,lags = 10
                                ,significance = 0.05
                                ,plot = TRUE){

  # Check if returns is numeric vector
  if (class(returns) != 'numeric'){
    stop('returns is not numeric vector')
  }

  results <- returns_fit(returns)

  if (plot == TRUE){

    diagnostic_plots(returns
                     ,lags = lags)

  }

  # Statistical tests
  LB <- Box.test(returns
                 ,lag = lags
                 ,type = 'Ljung-Box')

  if(LB$p.value < significance){
    print(paste(
      'p-value for Ljung-Box test for'
      ,lags[2]
      ,'lags is equal'
      ,round(LB$p.value, 4)
      ,'which means returns are not stationary.'
    ))
  } else{
    print(paste(
      'p-value for Ljung-Box test for'
      ,lags[2]
      ,'lags is equal'
      ,round(LB$p.value, 4)
      ,'which means returns are stationary.'
    ))
  }

  ADF <- tseries::adf.test(returns
                           ,alternative = 'stationary')

  if(ADF$p.value >= significance){
    print(paste(
      'p-value for ADF test is equal'
      ,round(ADF$p.value, 4)
      ,'which means returns are not stationary.'
    ))
  } else{
    print(paste(
      'p-value for ADF test is equal'
      ,round(ADF$p.value, 4)
      ,'which means returns are stationary.'
    ))
  }

  return(invisible(results))

}
pawel-wieczynski/PolishStock documentation built on March 23, 2022, 3:32 p.m.