Skip to content

Instantly share code, notes, and snippets.

@statwonk
Last active December 19, 2020 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save statwonk/232ff77e70db31b7ae3cda331357478a to your computer and use it in GitHub Desktop.
Save statwonk/232ff77e70db31b7ae3cda331357478a to your computer and use it in GitHub Desktop.
library(tidyverse)
library(quantmod)
library(gamlss)
select <- dplyr::select
posix <- function(x) { as.POSIXct(x, origin = "1970-01-01") }
## "Fat tails"
## Here we compare the residuals from the normal and t distributional models.
## Notice standardized error is worse in the normal model. This happens
## because returns are leptokurtic (large surprises should be expected, there's risk in stock returns),
# https://www.nasdaq.com/articles/fat-tail-risk-what-it-means-and-why-you-should-be-aware-it-2015-11-02
getSymbols("SHOP", src = "yahoo", from = "2017-01-01", to = "2020-12-01", auto.assign = FALSE) -> SHOP
SHOP %>%
as_tibble() %>%
mutate(date = posix(attributes(SHOP)$index)) %>%
arrange(date) %>%
mutate(first_difference = log(SHOP.Close) - log(lag(SHOP.Close))) %>%
filter(!is.na(first_difference)) -> SHOP
gamlss(first_difference ~ 1, data = SHOP) -> nfit
gamlss(first_difference ~ 1, data = SHOP, family = "TF", method = mixed(20, 20)) -> tfit
tibble(normal = residuals(nfit), t = residuals(tfit)) %>%
pivot_longer(cols = c(normal, t)) %>%
ggplot(aes(x = value, color = factor(name))) +
stat_ecdf() +
geom_point(stat = "ecdf") +
geom_vline(xintercept = 0) +
coord_cartesian(ylim = c(0, 0.05), xlim = c(-8, 0)) +
ggtitle("Lower tail of residuals") +
xlab("Scaled residuals") +
ylab("Quantiles") +
ggthemes::scale_color_colorblind(name = "Model") +
theme_bw() +
theme(axis.text = element_text(color = "black", size = 20))
plot(pacf(SHOP$first_difference))
Box.test (SHOP$first_difference, lag = 1, type = "Ljung")
plot(acf(SHOP$first_difference))
library(rugarch)
spec <- ugarchspec(variance.model = list(garchOrder = c(1, 1)))
fit <- ugarchfit(spec = spec, data = SHOP$first_difference, out.sample = 1)
show(fit)
plot(fit)
@statwonk
Copy link
Author

Screen Shot 2020-12-19 at 9 06 19 AM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment