分享

从暂元里取出子元素 | Stata编程

 对对子不错 2019-07-15

Stata在金融场景里使用的两个例子里,我们讨论了如何下载美联储加息前后两天的美国国债利率期限结构的数据。自从2017年以来,美国总共加过7次息, 2017年3月16, 6月15,12月14;2018年3月20,6月12,9月25和12月18日。

当时有位读者留言,说Stata因为没有列表格式,所以循环起来有点麻烦。最近想到了另外一个办法来解决这个问题。而这个办法的核心思想就是从定义的暂元集里取出子元素,这和列表(list)的思维有异曲同工之妙。

最初看到这个例子是在Stata官网,他们需要做一个平行(parallel)的循环,即从暂元集A取出的元素和暂元集B取出的元素要并列地展示在一起。下面这个例子:

local agrp 'cat dog cow pig'
local bgrp 'meow woof moo oinkoink '
local n : word count `agrp'
local m: word count `bgrp'

forvalues i = 1/`n' {
     local a : word `i' of `agrp'
     local b : word `i' of `bgrp'
     di '`a' says `b''
}

我们得到的结果是:

cat says meow
dog says woof
cow says moo
pig says oinkoink

如果我们掌握了这种从暂元集里取元素的循环方式,对于上面寻找加息前后两天数据的例子,我们可以使用如下的程序:

clear
freduse DGS30 DGS20 DGS10 DGS7 DGS5 DGS3 DGS2 DGS1 DGS6MO DGS3MO DGS1MO
save fred_data,replace

clear
input year month day
2017 3 16
2017 6 15
2017 12 14
2018 3 20
2018 6 12
2018 9 25
2018 12 18 
end

gen daten=mdy(month,day,year)
format daten %td
keep daten
levelsof daten,local(fdate)
save daten,replace


use fred_data,clear
keep if year(daten)>=2017

levelsof daten,local(fulldate)

local n : word count `fdate'
local m: word count `fulldate'


tempname memhold

postfile `memhold' day using date.dta,replace

forvalue i=1/`n'{
forvalue j=1/`m'{

local a : word `i' of `fdate'
local b : word `j' of `fulldate'

if `a'==`b'{

local b1 : word `=`j'-2' of `fulldate'
post  `memhold' (`b1') 
local b2 : word `=`j'-1' of `fulldate'
post  `memhold' (`b2') 
local b3 : word `=`j'+1' of `fulldate'
post  `memhold' (`b3') 
local b4 : word `=`j'+2' of `fulldate'
post  `memhold' (`b4') 

}
}
}

postclose `memhold'

use date,clear
format day %td
sort day

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多