Hello. I am working with daily time series data, and I want to create a lag that is exactly 1 month earlier. I did figure out a way to do so, but it's pretty inelegant - see below. Is there a better way to do this? I'm trying to this over a decent number of variables so I'm looking for a more efficient method.
The code below, which I found on the internet, basically creates a new lagged date that is exactly one month earlier. It then replaces the old date with the new lagged data. One disadvantage is that I have to do this for each lag, save into a new stata database file, and then merge with the original file.
Any help would be most appreciated!
Best,
Gene Park
clear
use xrate_daily.dta
gen monthlyDate=mofd(day) // day = is the specific day of a month in a specific year, e.g. Jan 1, 2017
gen oneMonthEarlierTemp=dofm(mofd(day)-1)
format oneMonthEarlierTemp %td
gen oneMonthEarlier=mdy(month(oneMonthEarlierTemp), day(day), year(oneMonthEarlierTemp))
format oneMonthEarlier %td
egen numInvalid=total(oneMonthEarlier==.)
local i 1 // number of days to subtract from invalid dates
while (numInvalid>0) {
replace oneMonthEarlier=mdy(month(oneMonthEarlierTemp),day (day)-`i',year(oneMonthEarlierTemp)) if oneMonthEarlier==.
local i=`i'+1
drop numInvalid
egen numInvalid = total(oneMonthEarlier==.)
}
drop oneMonthEarlierTemp numInvalid
format oneMonthEarlier %td
gen xrate_d_1m = xrate_d // xrate_d = daily exchange rate
keep oneMonthEarlier xrate_d_1m
rename oneMonthEarlier day
save xrate_daily.dta, replace // 1 month lag
The code below, which I found on the internet, basically creates a new lagged date that is exactly one month earlier. It then replaces the old date with the new lagged data. One disadvantage is that I have to do this for each lag, save into a new stata database file, and then merge with the original file.
Any help would be most appreciated!
Best,
Gene Park
clear
use xrate_daily.dta
gen monthlyDate=mofd(day) // day = is the specific day of a month in a specific year, e.g. Jan 1, 2017
gen oneMonthEarlierTemp=dofm(mofd(day)-1)
format oneMonthEarlierTemp %td
gen oneMonthEarlier=mdy(month(oneMonthEarlierTemp), day(day), year(oneMonthEarlierTemp))
format oneMonthEarlier %td
egen numInvalid=total(oneMonthEarlier==.)
local i 1 // number of days to subtract from invalid dates
while (numInvalid>0) {
replace oneMonthEarlier=mdy(month(oneMonthEarlierTemp),day (day)-`i',year(oneMonthEarlierTemp)) if oneMonthEarlier==.
local i=`i'+1
drop numInvalid
egen numInvalid = total(oneMonthEarlier==.)
}
drop oneMonthEarlierTemp numInvalid
format oneMonthEarlier %td
gen xrate_d_1m = xrate_d // xrate_d = daily exchange rate
keep oneMonthEarlier xrate_d_1m
rename oneMonthEarlier day
save xrate_daily.dta, replace // 1 month lag
Comment