I don't know why you have all the text/endtext. You can just build your SQL-Select as one long statement... just use a semi-colon at the end of each line to indicate that the statement continues on the following line (unlike in C# that ; indicates end of statement)...
Anyhow, this simplified should do what you have
SELECT ;
LEFT(ALLTRIM(group),ATC("|",ALLTRIM(group))-1) as Sim, ;
STREXTRACT(ALLTRIM(group),"|","|",1) as Company, ;
STREXTRACT(ALLTRIM(group),"|","|",2) as Fund, ;
STREXTRACT(ALLTRIM(group),"|","|",3) as LPG_level, ;
RIGHT(ALLTRIM(group),LEN(ALLTRIM(group)) - ATC("|",ALLTRIM(group),4)) as Output_group, ;
time, ;
SUM(as) as Asset_Share_Stressed, ;
SUM(as_us) as Asset_Share_Unstressed ;
FROM ;
( lcFile ) ;
GROUP BY ;
Sim, ;
Company, ;
Fund, ;
LPG_level, ;
Output_group, ;
time ;
ORDER BY ;
sim asc,;
output_group ASC ;
INTO ;
CURSOR bob
SELECT distinct LPG_Level ;
FROM Bob ;
INTO CURSOR C_TmpLevels
SELECT C_TmpLevels
SCAN
*/ You might have to be careful if the LPG_Level has spaces or special characters
*/ that might cause problems in file name creation, but at your discretion.
lcOutputFile = output_path + "LPG" + ALLTRIM( C_TmpLevels.LPG_Level ) + ".csv"
SELECT Bob
COPY TO ( lcOutputFile ) ;
FOR LPG_Level = C_TmpLevels.LPG_Level ;
TYPE csv
ENDSCAN
In this scenario, I just built your entire SQL query and ran it... From THAT result, I get distinct LPG_Level so it exactly matches the structure of the result set you have to work with. Notice in the "FROM" clause, I have the (lcFile) in parenthesis. This tells VFP to look to the variable name for the table name, not the actual table named "lcFile" as a literal. Similarly when I'm copying OUT to the CSV file... copy to (lcOutputFile).
Macros "&" can be powerful and useful, but can also bite you too especially if a file name path has a space in it... you are toast in that case... Try to get used to using parens in cases like this.