Skip to content

Instantly share code, notes, and snippets.

@IronistM
Created September 24, 2016 17:27
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 IronistM/811b754b8e2f4b88d7635e34dcdfa329 to your computer and use it in GitHub Desktop.
Save IronistM/811b754b8e2f4b88d7635e34dcdfa329 to your computer and use it in GitHub Desktop.
# *--------------------------------------------------------------------
#Adstock functions
adstock_calc_1<-function(media_var,dec,dim){
length<-length(media_var)
adstock<-rep(0,length)
for(i in 2:length){
adstock[i]<-(1-exp(-media_var[i]/dim)+dec*adstock[i-1])
}
adstock
}
adstock_calc_2<-function(media_var,dec,dim){
length<-length(media_var)
adstock<-rep(0,length)
for(i in 2:length){
adstock[i]<-1-exp(-(media_var[i]+dec*media_var[i-1])/dim)
}
adstock
}
#Function for creating test sets
create_test_sets<-function(base_p, trend_p, season_p, ad_p, dim, dec, adstock_form, error_std){
#National level model
#Five years of weekly data
week<-1:(5*52)
#Base sales of base_p units
base<-rep(base_p,5*52)
#Trend of trend_p extra units per week
trend<-trend_p*week
#Winter is season_p*10 units below, summer is season_p*10 units above
temp<-10*sin(week*3.14/26)
seasonality<-season_p*temp
#7 TV campaigns. Carry over is dec, theta is dim, beta is ad_p,
tv_grps<-rep(0,5*52)
tv_grps[20:25]<-c(390,250,100,80,120,60)
tv_grps[60:65]<-c(250,220,100,100,120,120)
tv_grps[100:103]<-c(100,80,60,100)
tv_grps[150:155]<-c(500,200,200,100,120,120)
tv_grps[200:205]<-c(250,120,200,100,120,120)
tv_grps[220:223]<-c(100,100,80,60)
tv_grps[240:245]<-c(350,290,100,100,120,120)
if (adstock_form==2){adstock<-adstock_calc_2(tv_grps, dec, dim)}
else {adstock<-adstock_calc_1(tv_grps, dec, dim)}
TV<-ad_p*adstock
#Error has a std of error_var
error<-rnorm(5*52, mean=0, sd=error_std)
#Full series
sales<-base+trend+seasonality+TV+error
#Plot
#plot(sales, type='l', ylim=c(0,1200))
output<-data.frame(sales, temp, tv_grps, week, adstock)
output
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment