Structural breaks in R: plotting trends

221 Views Asked by At

I'm trying to replicate the structure of the next grapich with ggplot2, but I did not find how to make it.

This is the graph i want to replicate

I have ts data and I want to add the regression lines for each of the structural breaks computed in my unit root test analysis.

 autoplot(merval_usd) +
  labs(x = "Año", y = "Log_Merval en USD")+
  theme_bw()

This is my data; it contains 4,888 observations on MERVAL price index.

> dput(head(merval_usd,20))
structure(c(6.31324002782979, 6.25952410104302, 6.27792086863394, 
6.26998603927151, 6.25789744652059, 6.25377111760352, 6.25553888702416, 
6.25132568135736, 6.32806177591735, 6.33873541097142, 6.34166356744438, 
6.35940084332373, 6.36564536517638, 6.36090516203878, 6.3456363608286, 
6.34242066971575, 6.33416733347983, 6.36629861166262, 6.36406205159053, 
6.34344097026516), class = c("xts", "zoo"), index = structure(c(946857600, 
946944000, 947030400, 947116800, 947203200, 947462400, 947548800, 
947635200, 947721600, 947808000, 948067200, 948153600, 948240000, 
948326400, 948412800, 948672000, 948758400, 948844800, 948931200, 
949017600), tzone = "UTC", tclass = "Date"), .Dim = c(20L, 1L
), .Dimnames = list(NULL, "MERV"))

Better looking

> head(merval_usd, 10)
           MERV
2000-01-03 6.313240
2000-01-04 6.259524
2000-01-05 6.277921
2000-01-06 6.269986
2000-01-07 6.257897
2000-01-10 6.253771
2000-01-11 6.255539
2000-01-12 6.251326
2000-01-13 6.328062
2000-01-14 6.338735

The breakpoints are calculated through this functions. It needs a modify version of the urca::ur.za function called ur.ka. This is the link to the repository with the ur.ka function to compile and execute.

Github repo

    for (i in 1){
  inicio<- Sys.time()
  urka <- ur.ka(merval_usd$MERV, model = 'trend', bp = 5) #bp5 y 12 lag, trend, se rechaza, con 24 rezagos tmbn es "bueno" el ajuste
  #bp5, 24, both
  fin<-Sys.time()
  print(urka)
  print(stringr::str_c("tiempo de ejecucion ", fin-inicio))
}

plot(urka$testreg$residuals)

plot<- ggplot(merval_usd, aes(x = Index, y = MERV))+params
bp<-vector("list", length = length(urka$bpoints))
count<-0
for(i in urka$bpoints){
  print(merval_usd[i])
  count = count+1
  bp[[count]]<- geom_vline(xintercept = as.Date(index(merval_usd$MERV[i])), color = "black", lwd = 0.5, lty=2)
  print(plot+bp)
}

params<- list(geom_line(linetype=1, lwd=1, colour="steelblue"),
              labs(title = "Log Indice Merval - período 2000-2020"),
              theme_minimal())

This is the graph i made

I did it with autoplot in order to get an idea of the data, but i'd like to complete and personalize with a ggplot2 graph.

I have my model ran and for each breakpoint, I estimated the intercept and trend coefficients; I don't know if this is enough.

So this is my first time posting a question here so, i apologize for the untidiness

0

There are 0 best solutions below