Skip to content

Instantly share code, notes, and snippets.

@Protonk
Created December 4, 2010 21:08
Show Gist options
  • Save Protonk/728482 to your computer and use it in GitHub Desktop.
Save Protonk/728482 to your computer and use it in GitHub Desktop.
A first crack at behavior of GDP growth
library(WDI)
library(ggplot2)
#Need it for GLS later
library(nlme)
growth.df<-WDI(country="all",indicator="NY.GDP.MKTP.KD.ZG",start=1961,end=2009,extra=TRUE);
growth.df<-subset(growth.df,growth.df$region != "Aggregates")
growth.df<-growth.df[,c(2:4)]
names(growth.df)<-c("country","year","growth")
growth.df$country<-as.factor(growth.df$country)
#I use complete.cases because it is cool and to avoid a bajillion warnings.
cc.growth.df<-growth.df[which(complete.cases(growth.df)),]
#Note that the number, mean and sd all have to come from the data, or else you don't have a very good simulation!
cc.growth.df$simulated<-rnorm(nrow(growth.df[which(complete.cases(growth.df)),]),mean=mean(growth.df[which(complete.cases(growth.df)),]$growth),sd=sqrt(mean(mean.growth$var)))
names(cc.growth.df)<-c("country","year","Empirical","Simulated")
#The X limits drop 1 or two outliers at 100% growth and a few more at ~60%.
estimated.plot<-ggplot(melt(cc.growth.df[,c(3,4)]))+geom_density(aes(x=value,colour=variable))+labs(x = NULL,y=NULL)+opts(title="Comparison of Empirical GDP Growth and \n Simulated Normal Data")+scale_colour_discrete(name='')+scale_x_continuous(limits=c(-50,50));
#OLS and GLS regressions for growth and variance. Residuals left in so that you can plot them with acf()
mean.growth<-ddply(growth.df,.(year),summarise,var=var(growth,na.rm=TRUE));
var.resid<-resid(lm(var~year,data=mean.growth));
var.gls<-gls(var~year,data=mean.growth,cor=corAR1(0.4));
#Very lazy very sloppy fractional dates for coloring in recessions. Don't do this at home, kids.
p.rstart<-c(1961,1969.9,1970.83,1973.83,1975.25,1980,1980.5,1981.65,1982.83,1990.65,1991.25,2001.25,2001.83,2007.9);
p.rend<-c(1969.9,1970.83,1973.83,1975.25,1980,1980.5,1981.65,1982.83,1990.65,1991.25,2001.25,2001.83,2007.9,2009.5);
p.isdownturn<-c(rep(c("no","yes"),7))
recessions<-as.data.frame(cbind(p.rstart,p.rend))
recessions$isdownturn<-p.isdownturn
names(recessions)<-c("rstart","rend","isdownturn")
#Plot using above dating. title is a little awkward. Notice how geom_rect() is used for the shading
var.recess.plot<-qplot(year,var,data=mean.growth,geom="line")+labs(x=NULL,y=NULL)+opts(title="Variance of Average Worldwide \nGrowth Rates with US Recessions")+geom_rect(aes(NULL,NULL,xmin=rstart,xmax=rend,fill=isdownturn),ymin=-Inf,ymax=Inf,data=recessions)+scale_fill_manual(name="NBER Dated \nRecessions",values=alpha(c("#cccccc","blue"),0.2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment