Stata是统计学专业软件,可以很方便的对数据处理,但几乎只能按照整行整列进行,而且每次只能加载一个矩阵(dta文件),如果要用到多个矩阵数据进行操作或进行复杂的循环控制,就力不从心了。
而Matlab工业界广泛使用的数据分析处理工具,对矩阵支持良好,除了可以像c语言一样完成底层的操作之外,还包含很多函数库,囊括工控、信号处理、金融、人工智能各个行业。虽然没有Stata内置的统计学函数全面,但在底层操作方面具有明显优势。
因此,在一次帮助别人完成金融数据分析时,尝试使用Stata对数据进行预处理,Matlab完成运算之后再由Stata完成进一步的加标签等操作。
Stata参考资料不多,主要参考了《应用Stata做统计分析》前两章基本操作部分,还有搜索。
待处理的数据为大盘行情与个股行情,从数据库下载到的数据为xls格式。使用
import excel *.xls import excel *.xls,clear#加载另一个文件
数据中一列为“1991-01-01”格式的日期数据,可以使用
generate dated=date(B,"YMD")
而day、month、year等函数可以由消逝天数计算出当天的年月日。
导入的数据均为字符串类型,要把字符串转换为数字,要使用
encode x,gen(y)
如果多个dta文件具有相同的列结构,可以采用下列命令合并:
use data1 append using data2 save data12
要删除本来为表格行列名的行,使用:
drop if dated==.
如果有些值是错误的,可以标记为error:
gen iserror="error" if acumrate==65535
xmlsave filename,doctype(excel)
drop,replace,ls,rename命令也经常用到。
Matlab中m文件编程可以完成很多操作,这次新学习到一个命令
try ... catch ... end
这次操作,用到了polyfit和polyval命令,分别是进行单变量多项式拟合和估计。
程序代码如下:
%company is sorted, need to change to no-sort %ind=563 company=[681,17902,563] is wrong,stock price's date may out of %range load('jr.mat') [m,n]=size(company); acum_index=zeros(m,1); errcompany=zeros(1,3);%error for which can't find stock price errind=1; for ind=1:m arit=zeros(40,1); com_id=company(ind,1);%company code com_date=company(ind,2);%company board date index_date_ind=find(ind399108(:,1)==com_date,1);%pointer to index if isempty(index_date_ind) index_date_ind=find(ind399108(:,1)==com_date+1,1); if isempty(index_date_ind) index_date_ind=find(ind399108(:,1)==com_date+2,1); end end % index 40befor 40after index_befor=ind399108(index_date_ind-40:index_date_ind-1,2); index_after=ind399108(index_date_ind:index_date_ind+39,2); %calc stock increase stock_tmp=stock(find(stock(:,1)==com_id,1,'first'):find(stock(:,1)==com_id,1,'last'),:); stock_tmp_ind=find(stock_tmp(:,2)==com_date,1); if isempty(stock_tmp_ind) stock_tmp_ind=find(stock_tmp(:,2)==com_date+1,1); if isempty(stock_tmp_ind) stock_tmp_ind=find(stock_tmp(:,2)==com_date+2,1); end end if isempty(stock_tmp_ind) errcompany(errind,:)=company(ind,:); errind=errind+1; acum_index(ind)=inf; continue end try stock_index_befor=(stock_tmp(stock_tmp_ind-40:stock_tmp_ind-1,2)-stock_tmp(stock_tmp_ind-40-1:stock_tmp_ind-1-1,2))./stock_tmp(stock_tmp_ind-40-1:stock_tmp_ind-1-1,2); stock_index_after=(stock_tmp(stock_tmp_ind:stock_tmp_ind+39,2)-stock_tmp(stock_tmp_ind-1:stock_tmp_ind+39-1,2))./stock_tmp(stock_tmp_ind-1:stock_tmp_ind+39-1,2); catch display(company(ind,:)); display(ind); acum_index(ind)=inf; continue; end %use index_befor stock_index_befor index_after stock_index_after to %calc p=polyfit(index_befor,stock_index_befor,1); arit=stock_index_after-polyval(p,index_after); acum_index(ind)=sum(arit); end outdata=[company,acum_index];
完成处理后,使用
xlswrite('x.xls',x)
之后可以在Stata中把消逝天数转换为日期,给变量重命名,就完成了操作。
这次工作完成的非常吃力,主要是工具的原因,Stata无法很好的完成循环控制等底层操作,Matlab虽然可以完成所有操作但Matlab中的字符串和日期操作非我所长,R语言作为专业统计语言,完成这些数据处理和计算应该是十分方便的。很期待R的表现。