打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

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
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
别告诉我你会用WORD
Pearson和Spearman相关系数同时导入word,技巧在这里!
DGS-03系列电磁阀 液压阀03-3C2/03-3C4/03-3C6/03-3C60换向阀
Stata绘图:绘制二维地图
【原创】stata介绍之outreg2 logout,从简单到基础,涵盖描述相关 回归,从时间到面板...
修改成绩被起诉了
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服