I have to create a user-defined weighting function that weighs the independent variable using a particular formula and then I have to run an ordered probit of the dependent variable on the independent variable. To define the user-defined function, I am using python in Stata and to do the ordered probit, I want to use Stata oprobit command as I cannot find a package on python that does this. Now I am facing an issue in interacting both python syntax and stata syntax within the same code block. I am giving a simplified version of my code below:
Code:
python:
#Execute loop to define Ait for each i, lambda in lambda_list and perform regression
#lambda_list is static for each iteration. needs to be manually updated after each iteration depending on the prior iteration's results
for l in lambda_list:
for name in var_name:
for j in index_s: #range(N):
i = j
#print(i)
k = k_val(i,k_bar, age)
if(math.isnan(k)):
#pass
print("This ID has a null value for k given by : ", k)
else:
#print(k)
#print(i)
data.at[i,'Ait_'+name] = Ait(age,l,k,i,name)
d = data[['ics_new','Ait_'+name, 'igdpratio', 'pchange_realpc_usasartmismei', 'lei', 'tb3ms', 'gs10', 'sex_dummy', 'married_dummy', 'age3', 'age3_sq', 'educ_hs', 'educ_col', 'region_nc', 'region_ne', 'region_s', 'pchange_realsp500', 'pchange_indpro']]
d = d.dropna()
Y = d['ics_new']
X = d[['Ait_'+name, 'igdpratio', 'pchange_realpc_usasartmismei', 'lei', 'tb3ms', 'gs10', 'sex_dummy', 'married_dummy', 'age3', 'age3_sq', 'educ_hs', 'educ_col', 'region_nc', 'region_ne', 'region_s', 'pchange_realsp500', 'pchange_indpro']]
X = sm.add_constant(X.to_numpy())
model = sm.OLS(Y,X)
results = model.fit()
b['b_OLS_'+str(name)+'_'+str(l)] = [results.params]
t['t_OLS_'+str(name)+'_'+str(l)] = [results.tvalues]
R['Rsquared_'+str(name)+'_'+str(l)] = [results.rsquared]
e_2['SSR_OLS_'+str(name)+'_'+str(l)] = [SSR(np.array(b['b_OLS_'+str(name)+'_'+str(l)])[0],Y, X)]
end
0 Response to Running stata commands within python: end blocks in Stata 16
Post a Comment