--- title: "Historical autocorrelations in stock prices" output: html_document --- Christian Bartels, January 2015, Allschwil ####Code of: Historical autocorrelations in stock prices. Christian Bartels. figshare. http://dx.doi.org/10.6084/m9.figshare.1287224 ####Available at: Code - Historical autocorrelations in stock prices. Christian Bartels. figshare. http://dx.doi.org/10.6084/m9.figshare.1287230 ```{r} rm(list=ls(all=TRUE)) require(Quandl) require(lubridate) require(data.table) require(gamlss) require(gamlss.add) require(ggplot2) # print out version information, path, date R.Version() date() Sys.info() ``` ```{r results='hide', echo=FALSE} # Quandl.auth("...") ``` ```{r} # start of time stime<-ymd("1900-1-1") # sp500 symbol <- "YAHOO/INDEX_GSPC" d1 <- as.data.table(Quandl(symbol)) d2 <- data.table(d1) d2[,Date:=ymd(Date)] setkey(d2,Date) d2[,Time:=as.double(difftime(Date,stime,units="days"))] d2[,year:=year(Date)] d2[,dec:=(year%/%10)*10] d2[,yday:=yday(Date)] d2[,DV1a:=log(Close)] d2[,DV2a:=c(tail(DV1a,-1),rep(NA,1))] d2[,DELa:=DV2a-DV1a] ``` ```{r} ggplot(d2,aes(x=Date,y=DV1a)) + geom_point() + ylab(paste0("Natural log of ",symbol)) ``` ```{r} d3<-na.omit(d2) d3[,w1:=0] d3[dec==1960,w1:=1] d3[1:25,w1:=0] l1 <- gamlss(DELa~ la(DELa, lags=20, order=1, from.lag=1), sigma.fo=~la(DELa^2, lags=10, order=1, from.lag=1), weights=w1, family=TF, data=d3) wp(l1,ylim.all=1) plot(l1, ts=TRUE) d3[,w2:=0] d3[dec==2000,w2:=1] d3[1:25,w2:=0] l2 <- gamlss(DELa~ la(DELa, lags=20, order=1, from.lag=1), sigma.fo=~la(DELa^2, lags=10, order=1, from.lag=1), weights=w2, family=TF, data=d3) ``` ```{r} d3[,PRED1:=predict(l1)] d3[,PRED2:=predict(l2)] labs <- c("decrease","no change","increase") ggplot(d3,aes(x=cut_number(PRED1,3,labels=labs),y=DELa*10000,colour=factor(dec))) + stat_summary(fun.data = "mean_cl_boot",size=2) + facet_grid(~dec) + ylab("Actual change in basis points (mean, 95%CI)") + xlab("Predicted change") + ggtitle("Model based on data of the 60's") + theme_bw()+ theme(axis.text.x = element_text(angle = 45, hjust = 1)) + guides(colour=guide_legend(title="decade")) ggplot(d3,aes(x=cut_number(PRED2,3,labels=labs),y=DELa*10000,colour=factor(dec))) + stat_summary(fun.data = "mean_cl_boot",size=2) + facet_grid(~dec) + ylab("Actual change in basis points (mean, 95%CI)") + xlab("Predicted change") + ggtitle("Model based on data of the 00's")+ theme_bw()+ theme(axis.text.x = element_text(angle = 45, hjust = 1)) + guides(colour=guide_legend(title="decade")) ``` ```{r} write.csv(d3,file="quandlGamlss12_data.csv",quote=FALSE,row.names=FALSE) ```