#' Returns Plot function
#'
#' Plot histogram of returns alongside with empirical density, fitted normal density and fitted t-Student density. Plot ACF and qq-plots.
#' @param returns Numeric vector of asset returns
plot_histogram_with_density <- function(returns){
# Check if returns is numeric vector
if (class(returns) != 'numeric'){
stop('returns is not numeric vector')
}
params <- returns_fit(returns)
n <- 10*length(returns)
sample_density <- density(returns)
t_density <- density(params$t_param[1] +
rt(n, params$t_param[3]) *
params$t_param[2])
normal_density <- density(rnorm(n, params$norm_param[1]
,params$norm_param[2]))
hist(returns
,breaks = 'FD'
,freq = FALSE
,xlab = ''
,ylab = '')
lines(sample_density
,col = 'blue'
,lwd = 3)
lines(t_density
,col = 'orange'
,lwd = 3)
lines(normal_density
,col = 'forestgreen'
,lwd = 3)
legend('left'
,legend = c('Sample density'
,'t-Student density'
,'Normal density')
,col = c('blue'
,'orange'
,'forestgreen')
,bg = 'transparent'
,lty = c(1,1,1)
,lwd = c(3,3,3)
,box.lty = 0)
}
plot_qq <- function(returns){
# Check if returns is numeric vector
if (class(returns) != 'numeric'){
stop('returns is not numeric vector')
}
params <- returns_fit(returns)
n <- length(returns)
# t-student QQ-plot
xx <- quantile(params$t_param[1] +
qt(seq(0, 1, by = 0.01)
,df = params$t_param[3]) *
params$t_param[2]
,c(0.25, 0.75))
yy <- quantile(returns
,c(0.25, 0.75))
slope <- (yy[2] - yy[1]) / (xx[2] - xx[1])
intercept <- yy[1] - slope*xx[1]
qqplot(x = params$t_param[1] +
qt(seq(0, 1, length.out = n)
,df = params$t_param[3]) *
params$t_param[2]
,y = returns
,col = 'blue'
,xlab = ''
,ylab = ''
,main = 't-Student QQ-plot')
abline(a = intercept
,b = slope
,col = 'orange'
,lwd = 3)
# Normal QQ-plot
xx <- quantile(qnorm(seq(0, 1, by = 0.01)
,mean = params$norm_param[1]
,sd = params$norm_param[2])
,c(0.25, 0.75))
yy <- quantile(returns
,c(0.25, 0.75))
slope <- (yy[2] - yy[1]) / (xx[2] - xx[1])
intercept <- yy[1] - slope*xx[1]
qqplot(x = qnorm(seq(0, 1, length.out = n)
,mean = params$norm_param[1]
,sd = params$norm_param[2])
,y = returns
,col = 'blue'
,xlab = ''
,ylab = ''
,main = 'Normal QQ-plot')
abline(a = intercept
,b = slope
,col = 'orange'
,lwd = 3)
}
diagnostic_plots <- function(returns, lags = 10){
# Check if returns is numeric vector
if (class(returns) != 'numeric'){
stop('returns is not numeric vector')
}
par(mfcol = c(2,2))
plot_histogram_with_density(returns)
acf(returns
,lag.max = lags
,main = 'Autocorrelation of returns')
plot_qq(returns)
par(mfcol = c(1,1))
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.