在公司金融研究中经常会碰到移动平均和前几期标准差的计算,主要采用两个命令:tssmooth ma 和rowsd.
1.移动平均:
Title
[TS] tssmooth ma -- Moving-average filter
Syntax
Moving average with uniform weights
tssmooth ma [type] newvar(生成新的变量名称) =exp [if] [in](要被平均的变量表达式), window(#l[#c[#f]])
[replace]
Moving average with specified weights
tssmooth ma [type] newvar = exp [if] [in], weights([numlist_l] <#c>
[numlist_f]) [replace]
You must tsset your data before using tssmooth ma; [TS] tsset.
特别注意:window(#l[#c[#f]])是指移动的时间窗口,表示几期移动平均,比如5期移动平均那么就是window(5 1),表示从第1期到第5期的移动平均数。
2.行标准差
需要与egen 配合使用,比如要生成前三期变量a的标准差,那么先要生成前面滞后三期变量,L1a,L2a,L3a,然后采用如下 命令:
auto.dta,clear
tsset year
gen L1a=L.a
gen L2a=L2.a
gen L3a=L3.a
egen sda3=rowsd(L1a L2a L3a)
注意: rowsd(varlist) may not be combined with by. It creates the (row) standard
deviations of the variables in varlist, ignoring missing values.