Bookmark and Share

Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down on April 23, and its replacement, statalist.org is already up and running.


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

st: nested foreach


From   "Fabian Schönenberger" <sch.f@gmx.ch>
To   statalist@hsphsun2.harvard.edu
Subject   st: nested foreach
Date   Fri, 21 Sep 2012 15:29:40 +0200

Dear Statalist
I want to calculate returns for portfolio consisting of stocks. I have several variables [var] indicating to which portfolio a certain company belongs to. These variables have numbers from 1 to 10, 1 to 5 and sometimes a combination of two numbers like 1 11 12 21 and so on. 
In order to automate the calculation I tried the following formula:

foreach var in `varlist' {
levelsof `var',local(levels)
foreach l of local levels {
egen `var'_return_`l'=mean(totalreturn) if `var'==`l', by(date_mt)
bysort date_mt:egen `var'_return_`l'_total=mean(`var'_return_`l')
drop `var'_return_`l'
egen `var'_wtreturn_`l'=wtmean(totalreturn) if `var'==`l', weight(Lmarketcap_total) by(date_mt)
bysort date_mt:egen `var'_wtreturn_`l'_total=mean(`var'_wtreturn_`l')
drop `var'_wtreturn_`l'
}}

However, I only get the first two portfolio returns, and then Stata says: 

program error:  code follows on the same line as close brace
r(198)

Stata should start using the first variable, then do all steps for these variable at each level of the variable, and the continue to the next variable.

How do I have to change the commands? 

Many thanks in advance, 

FS
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/


© Copyright 1996–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index