I am trying to write a wrapper using GMM. When I do it manually, it converges very fast and provides me coefficients and SE. However, when I write it with a loop, it does not converge. Could anyone help me, please? Followings are my manual and automatic programs:

Manual one:


HTML Code:
clear all
program define svywt
syntax varlist, wtvar(varlist)
    
    gettoken depvar indepvars : varlist
    _fv_check_depvar `depvar'
    local p: word count `wtvar'
    local first1(`:word 1 of `wtvar''/(1+{xb: `wtvar'}))
    
    local first2(`:word 2 of `wtvar''/(1+{xb: }))
    
    local last(last:(`depvar' - ({`depvar': `indepvars' _cons}))/    (1+{xb: }))
    local last_inst instruments(last:`indepvars')
    
    gmm `first1'`-'`first`p'' `last', `last_inst' onestep winitial(unadjusted, independent)
        
    end

sysuse auto, clear
egen y = mean(price)

gen price_1 = price -y

egen x = mean(mpg)

gen mpg_1=mpg-x

svywt price weight mpg, wtvar(price_1 mpg_1)

With a loop:


HTML Code:
clear all
program define svywt
syntax varlist, WTvar(varlist)
    
    gettoken depvar indepvars : varlist
    _fv_check_depvar `depvar'
    
    local p: word count `wtvar' 
     
    forvalues i = 2(1)`p'{
     local first_1(first_1:`:word `i' of `wtvar''/(1+{xb: `wtvar'} )) //this one is done manually to declare linear combination `xb'
     local first_`i'(first_`i':`:word `i' of `wtvar''/(1+ {xb:}) )
    }
    local third(third:(`depvar' - ({`depvar': `indepvars' _cons}))/    (1+{xb:} ))
    local third_inst instruments(third: `indepvars')
    
    gmm `first_1'`-'`first_`p'' `third', `third_inst' onestep winitial(unadjusted, independent)
        
    end

sysuse auto, clear
egen y = mean(price)

gen price_1 = price -y

egen x = mean(mpg)

gen mpg_1=mpg-x

svywt price weight mpg, wtvar(price_1 mpg_1)
I need a loop because if I have 100 equations, I can accommodate them easily. Thank you so much.

Rabiul