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 at the end of May, and its replacement, is already up and running.

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

Re: st: nested foreach

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

I would try changing





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

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