Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.


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

Re: st: nested foreach


From   Nick Cox <[email protected]>
To   [email protected]
Subject   Re: st: nested foreach
Date   Fri, 21 Sep 2012 14:34:02 +0100

I would try changing

}}

to

}
}

Nick

On Fri, Sep 21, 2012 at 2:29 PM, "Fabian Schönenberger" <[email protected]> wrote:
> 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?
>

*
*   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–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index