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, is already up and running.

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

st: nested foreach

From   "Fabian Schönenberger" <>
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

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, 

*   For searches and help try:

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