Structural models I: simultaneous equations and structural equation models
Study structural and reduced forms, order and rank identification, 2SLS and 3SLS, latent-variable structural equation models and the Lucas critique of policy extrapolation.
After this lesson you can
- Derive a linear system's reduced form and show why structural parameters require restrictions.
- Apply order and rank conditions to two- and three-equation systems.
- Estimate systems by 2SLS and 3SLS and compare efficiency.
- Specify and estimate a two-latent-variable SEM through its implied covariance.
- Explain the Lucas critique and connect it to mechanism invariance in causal models.
Before you start
An equilibrium does not reveal its curves
You observe market prices and quantities over years. Each point is the intersection of supply and demand, not an observation obtained by moving price while everything else is held fixed. As seen in simultaneity, shifts of both curves can mix their slopes.
In 1943 Haavelmo posed the question for complete systems: can different theoretical parameters generate the same observations? Before optimizing a fit, identify which variation and restrictions could distinguish explanations.
Structural and reduced form
In a linear simultaneous-equations system with endogenous variables and exogenous , write
if is invertible. Structural and reduced forms answer different questions: and capture assumed simultaneous relationships; describes how endogenous variables change with after solving the system. Reduced covariance is , where . Knowing and that covariance does not necessarily determine , and .
For example, if you observe only with independent bivariate standard normal distribution, for any you can write and , defining and . Slopes change, but the observable distribution is exactly the same if shock covariance may change. Would requiring independent shocks suffice? The first exercise asks you to investigate that restriction. Equations do not themselves identify which curve is which; additional defensible restrictions are needed.
Order and rank: counting is not enough
Normalize the dependent-variable coefficient of the equation studied to one and define . Assume known exclusion restrictions, invertible and model exogeneity and regularity. For equation , remove its row from and retain columns of variables excluded from that equation, endogenous and exogenous. The rank condition requires that submatrix have rank .
The order condition counts excluded columns: at least are needed. It is necessary, but columns can be linearly dependent. If rank is lower, the equation is not identified by these exclusions. With full rank, the minimum number of exclusions gives exact identification; more exclusions give overidentification in this scheme. These are equation-by-equation identification conditions under specified restrictions; additional cross-equation restrictions can provide information not counted here.
The algebraic intuition is to seek a combination of other structural rows that can be added to row without changing any exclusion or normalization. If the excluded-column submatrix has a nontrivial left null space, a direction of indistinguishable combinations remains. Full rank removes that local ambiguity under the other assumptions; counting columns without checking independence does not.
2SLS and 3SLS
Once an equation is identified and instruments valid, 2SLS estimates it separately. LIML is another single-equation option whose distribution can differ with weak instruments. To exploit cross-equation shock correlation, three-stage least squares combines instruments and system GLS:
- Project each equation’s regressors onto the common instrument space, including exogenous controls.
- Obtain initial estimates and estimate contemporaneous covariance of structural residuals.
- Stack equations and apply instrumental GLS with that estimated covariance.
If is the block design with projected columns and cross-equation error covariance, one form with common instruments is
The formula assumes rank, invertibility and the stated stacking order. To interpret it as efficient GLS in this model, stacked covariance must be : the same contemporaneous covariance and no correlation across observations. Heteroskedasticity or dependence requires adapting covariance and inference. With correct specification and suitable assumptions it can improve asymptotic efficiency over separate equation estimation; a particular sample need not show lower error in every coefficient. If an equation or instrument is invalid, joint weighting can transmit the problem to other equations. FIML estimates jointly by maximum likelihood and needs additional distributional and specification assumptions. IV3SLS documentation shows a system implementation.
Latent variables and covariances
A structural equation model separates a measurement model from relationships between latent variables. For example, with six indicators and two factors :
If has variance , variance , they are independent and measurement errors have diagonal matrix independent of factors, implied covariance is
These independences are model restrictions, not automatic indicator properties. Fixing one loading per factor to one defines its scale; without equivalent normalization, multiplying a factor and dividing its loadings leaves covariances unchanged. Local identification must also be checked: having more moments than parameters is necessary but does not guarantee a full-rank Jacobian.
The measurement model extends factor analysis by adding relationships between factors. Under linear Gaussian assumptions and an acyclic graph, it can also be expressed as a Bayesian network with latent nodes. In simulation calibration the same question recurs: different parameters can produce indistinguishable observations.
For iid Gaussian observations, with sample covariance calculated using divisor and positive-definite , normalized discrepancy relative to the saturated model is
Under a correct model, identification and regularity, is compared asymptotically with chi-square whose degrees of freedom equal independent moments minus free parameters; some covariance conventions use . A singular matrix or boundary solution can invalidate usual error calculation and asymptotic reference. RMSEA and CFI summarize discrepancies relative to degrees of freedom or a baseline model; they depend on conventions and are not tests of causal truth.
Covariances of indicators have distinct entries. Counting free parameters against those entries, called the rule, is only a necessary check. Different graphs can imply the same matrix and obtain identical fit: good overall fit does not determine causal direction. Scale restrictions, temporal information, interventions and substantive assumptions can help distinguish models.
A rule that changes expectations
The Lucas critique warns that a relationship estimated under one policy can change when agents anticipate another. In the example, expected taxes follow and the assumed mechanism is , with . The reduced form is
Changing or changes reduced-form intercept or slope even if and stay fixed. The graph calibrates the mechanism once and recalculates expectations under the new rule; the old reduced-form line is not updated. This is a synthetic experiment: invariance is imposed to teach the mechanism, not deduced by calling the model structural. The policy-and-expectations formulation is in Lucas.
The cell reproduces the interactive’s generator and predictions, retaining the same evaluation sample across three rules.
import math
import numpy as np
def rng_js(seed):
a=seed & 0xffffffff
spare=None
def uniform():
nonlocal a
a=(a+0x6d2b79f5)&0xffffffff
t=((a^(a>>15))*(a|1))&0xffffffff
t=(t^((t+((t^(t>>7))*(t|61)))&0xffffffff))&0xffffffff
return ((t^(t>>14))&0xffffffff)/4294967296
def normal():
nonlocal spare
if spare is not None:
value,spare=spare,None
return value
u=uniform()
while u==0: u=uniform()
v=uniform()
while v==0: v=uniform()
radius=math.sqrt(-2*math.log(u))
spare=radius*math.sin(2*math.pi*v)
return radius*math.cos(2*math.pi*v)
return normal
normal=rng_js(270801)
income=np.linspace(.5,9.5,80)
train=2+.7*(income-(1+.2*income))+.5*np.array([normal() for _ in income])
noise=.5*np.array([normal() for _ in income])
intercept,slope=np.linalg.lstsq(np.column_stack((np.ones(len(income)),income)),train,rcond=None)[0]
beta=slope/.8
alpha=intercept+beta
print('Entrenamiento: intercepto, pendiente, alfa y beta recuperados:',intercept,slope,alpha,beta)
for name,a,b in [('original',1.,.2),('progresiva',2.,.6),('devolución',.5,-.1)]:
y=2+.7*(income-a-b*income)+noise
reduced=intercept+slope*income
structural=alpha+beta*(income-a-b*income)
rmse_reduced=np.sqrt(np.mean((y-reduced)**2))
rmse_structural=np.sqrt(np.mean((y-structural)**2))
print(name,'regla:',a,b,'RMSE reducida y mecanismo:',rmse_reduced,rmse_structural)
if name=='original': assert np.allclose(reduced,structural)Autonomy of a mechanism means it continues to describe the variable under the particular intervention, not immunity to every conceivable policy. Haavelmo attributes the term and several ideas to a 1938 Frisch memorandum. This question connects system modeling with causal models: justify which equation changes, which remain and how expectations respond.
Lab: identification and 3SLS
The simulated system has exactly identified demand and overidentified supply. The first cell calculates rank, reduced form and estimators; the second compares squared errors across paired replicates. Zeros are assumed restrictions and instruments are exogenous by construction.
Across 500 replicates, the 2SLS-minus-3SLS MSE difference for the demand price coefficient is approximately 0.0000035 versus Monte Carlo error 0.0000601: here it does not resolve a gain. For two demand shifters differences are 0.000808 and 0.001088, with Monte Carlo errors 0.000205 and 0.000241. These figures describe the cell’s generator, not a guaranteed improvement for any system. The lab treats only exact zeros as exclusions; rank tolerance is numerical and stated in the function.
"""Oferta y demanda: rango, forma reducida, MC2E y MC3E reproducibles.
Modelo B y + Gamma z = u. B tiene diagonal no nula y es invertible.
Los ceros suministrados representan exclusiones estructurales asumidas.
"""
import numpy as np
def identification(B, Gamma, eq, tol=1e-10):
B, Gamma = np.asarray(B, float), np.asarray(Gamma, float)
m = B.shape[0]
if (B.shape != (m, m) or Gamma.ndim != 2 or Gamma.shape[0] != m or
not 0 <= eq < m or not np.isfinite(B).all() or not np.isfinite(Gamma).all() or
np.any(np.abs(np.diag(B)) <= tol) or np.linalg.matrix_rank(B) < m):
raise ValueError('Sistema, normalización o valores inválidos')
omitted_y = [j for j in range(m) if j != eq and B[eq,j] == 0]
omitted_z = np.flatnonzero(Gamma[eq] == 0)
rows = np.arange(m) != eq
constraints = np.column_stack((B[rows][:, omitted_y], Gamma[rows][:, omitted_z]))
order = constraints.shape[1]
rank = np.linalg.matrix_rank(constraints, tol=tol) if order else 0
if rank < m-1:
state = 'no identificada'
else:
state = 'exacta' if order == m-1 else 'sobreidentificada'
return state, order, rank
def simulate_market(n, rng):
z = rng.normal(size=(n, 3))
common, independent = rng.normal(size=(2, n))
ud = common
us = .65*common + np.sqrt(1-.65**2)*independent
alpha_d, beta_d = 2., -.8
alpha_s, beta_s = .5, .7
g1, g2, g3 = .9, -.55, .8
# Qd=alpha_d+beta_d*P+g1*z1+g2*z2+ud
# Qs=alpha_s+beta_s*P+g3*z3+us; impone Qd=Qs.
price = (alpha_s-alpha_d-g1*z[:,0]-g2*z[:,1]+g3*z[:,2]+us-ud)/(beta_d-beta_s)
quantity = alpha_d+beta_d*price+g1*z[:,0]+g2*z[:,1]+ud
Xd = np.column_stack((np.ones(n),price,z[:,0],z[:,1]))
Xs = np.column_stack((np.ones(n),price,z[:,2]))
instruments = np.column_stack((np.ones(n),z))
return quantity, price, Xd, Xs, instruments
def system_3sls(y, designs, Z):
"""MC3E factible sin corrección finita; misma Z para cada ecuación."""
y, Z = np.asarray(y,float), np.asarray(Z,float)
qz, _ = np.linalg.qr(Z,mode='reduced')
fitted = [qz@(qz.T@X) for X in designs]
tsls = [np.linalg.lstsq(Xhat,y,rcond=None)[0] for Xhat in fitted]
residuals = np.column_stack([y-X@b for X,b in zip(designs,tsls)])
omega = residuals.T@residuals/len(y)
if np.linalg.matrix_rank(omega) < len(designs):
raise ValueError('Covarianza de ecuaciones singular')
invomega = np.linalg.inv(omega)
blocks = [[invomega[i,j]*(fitted[i].T@fitted[j])
for j in range(len(designs))] for i in range(len(designs))]
right = np.concatenate([sum(invomega[i,j]*(fitted[i].T@y)
for j in range(len(designs)))
for i in range(len(designs))])
beta = np.linalg.solve(np.block(blocks),right)
split = np.cumsum([X.shape[1] for X in designs])[:-1]
return tsls, np.split(beta,split), omega
B = np.array([[1., .8], [1., -.7]])
Gamma = np.array([[-.9,.55,0.],[0.,0.,-.8]])
for eq in range(2):
print('Ecuación, identificación, exclusiones, rango:', eq, *identification(B,Gamma,eq))
B_counter = np.array([[1., .2, .1], [.2, 1., .3], [.3, .1, 1.]])
G_counter = np.array([[0.,0.,1.],[1.,2.,.5],[2.,4.,-.3]])
counter = identification(B_counter,G_counter,0)
assert counter == ('no identificada', 2, 1)
print('Tres ecuaciones: orden satisfecha, rango insuficiente:', counter)
Pi = -np.linalg.solve(B,Gamma)
print('Matriz de forma reducida Π=−B⁻¹Γ:', Pi)
assert np.allclose(B@Pi+Gamma,0.)
rng = np.random.default_rng(270801)
y, price, Xd, Xs, Z = simulate_market(1200,rng)
own_2, own_3, omega = system_3sls(y,[Xd,Xs],Z)
print('MC2E demanda y oferta:',*own_2)
print('MC3E demanda y oferta:',*own_3)
print('Covarianza de residuos estructurales estimada:',omega)
print('Coeficientes de precio verdaderos: demanda -0,8; oferta 0,7.')
print('La clasificación usa exclusiones asumidas y el rango; no verifica exogeneidad.')"""Comparación Monte Carlo apareada; requiere la celda system_laboratory."""
import numpy as np
rng_mc = np.random.default_rng(270802)
repetitions, n_mc = 500, 250
errors, demand_errors = [], []
for _ in range(repetitions):
yy, _, xd, xs, zz = simulate_market(n_mc, rng_mc)
b2, b3, _ = system_3sls(yy, [xd, xs], zz)
errors.append([b2[0][1]+.8, b3[0][1]+.8, b2[1][1]-.7, b3[1][1]-.7])
demand_errors.append([b2[0]-np.array([2.,-.8,.9,-.55]),
b3[0]-np.array([2.,-.8,.9,-.55])])
errors = np.asarray(errors)
demand_errors = np.asarray(demand_errors)
delta_sq = errors[:,[0,2]]**2-errors[:,[1,3]]**2
delta_demand = demand_errors[:,0,:]**2-demand_errors[:,1,:]**2
print('Réplicas y n:', repetitions, n_mc)
print('Sesgo medio demanda MC2E/MC3E y oferta MC2E/MC3E:', errors.mean(axis=0))
print('ECM demanda MC2E/MC3E y oferta MC2E/MC3E:', np.mean(errors**2,axis=0))
print('ECM MC2E menos MC3E, demanda/oferta:', delta_sq.mean(axis=0))
print('Error Monte Carlo de diferencias apareadas de ECM:', delta_sq.std(axis=0,ddof=1)/np.sqrt(repetitions))
print('ECM MC2E menos MC3E, todos los coeficientes de demanda:', delta_demand.mean(axis=0))
print('Error Monte Carlo apareado, todos los coeficientes:', delta_demand.std(axis=0,ddof=1)/np.sqrt(repetitions))
print('Eficiencia de sistema presupone ecuaciones correctas; los resultados son de este diseño.')This local comparison exactly regenerates the preceding data. Install linearmodels and NumPy in your environment; ols denotes equation-wise instrumental estimation and gls uses system 3SLS in this API.
"""Comparación autocontenida con linearmodels, instalable en entorno local."""
import numpy as np
from linearmodels.system import IV3SLS
rng = np.random.default_rng(270801)
n = 1200
z = rng.normal(size=(n,3))
common, independent = rng.normal(size=(2,n))
ud = common
us = .65*common + np.sqrt(1-.65**2)*independent
price = (.5-2.-.9*z[:,0]+.55*z[:,1]+.8*z[:,2]+us-ud)/(-.8-.7)
quantity = 2.-.8*price+.9*z[:,0]-.55*z[:,1]+ud
one = np.ones((n,1))
equations = {
'demanda': {'dependent':quantity, 'exog':np.column_stack((one,z[:,0],z[:,1])),
'endog':price[:,None], 'instruments':z[:,[2]]},
'oferta': {'dependent':quantity, 'exog':np.column_stack((one,z[:,2])),
'endog':price[:,None], 'instruments':z[:,[0,1]]},
}
model = IV3SLS(equations)
for method in ('ols','gls'):
fit = model.fit(method=method,debiased=False)
demand = fit.equations['demanda'].params.to_numpy()[[0,3,1,2]]
supply = fit.equations['oferta'].params.to_numpy()[[0,2,1]]
print('IV3SLS método',method,'demanda y oferta:',demand,supply)
print('Orden: intercepto, precio y desplazadores; compara con el laboratorio propio.')npm run lab and open the connection link.Lab: SEM by maximum likelihood
The first two cells estimate a synthetic six-indicator SEM. Two loadings are anchored and the Jacobian, observed Hessian and global test are calculated. Run the definition first, then data generation. The example uses a different sample from the interactive figure.
In the simulated sample of 800 observations, the between-factor coefficient is 0.60598 with observed standard error 0.03807. The global test gives with 8 degrees of freedom and ; the Jacobian has rank 13. semopy reproduces parameters and fit, with a somewhat different standard error because it defaults to expected information. None of these results proves causal direction between factors.
import numpy as np
from scipy.optimize import minimize
from scipy.special import gammaincc
# Dos latentes de media cero: eta = beta * xi + zeta.
# Las cargas del primer indicador de cada bloque se fijan a 1.
def sem_cov(t, deriv=False):
beta, l2, l3, l5, l6 = t[:5]
v = np.exp(t[5:]) # Var(xi), Var(zeta), seis varianzas de error
a, c = v[:2]
L = np.array([[1,0],[l2,0],[l3,0],[0,1],[0,l5],[0,l6]], float)
P = np.array([[a,beta*a],[beta*a,beta*beta*a+c]])
Sigma = L @ P @ L.T + np.diag(v[2:])
if not deriv:
return Sigma
ds = []
dP = np.array([[0,a],[a,2*beta*a]])
ds.append(L @ dP @ L.T)
for row, col in [(1,0),(2,0),(4,1),(5,1)]:
dL = np.zeros((6,2)); dL[row,col] = 1
ds.append(dL @ P @ L.T + L @ P @ dL.T)
ds.append(L @ np.array([[a,beta*a],[beta*a,beta*beta*a]]) @ L.T)
ds.append(L @ np.array([[0,0],[0,c]]) @ L.T)
for i in range(6):
d = np.zeros((6,6)); d[i,i] = v[i+2]; ds.append(d)
return Sigma, np.array(ds)
def sem_objective(t, S):
Sigma, ds = sem_cov(t, True)
sign, logdet = np.linalg.slogdet(Sigma)
if sign <= 0:
raise ValueError('La covarianza implicada debe ser positiva definida')
inv = np.linalg.inv(Sigma)
loss = logdet + np.trace(S @ inv)
grad = np.einsum('ij,kji->k', inv - inv @ S @ inv, ds)
return loss, grad
def sem_fit(data):
n, p = data.shape
if p != 6 or n <= p:
raise ValueError('Se requieren seis indicadores y n > 6')
centered = data - data.mean(axis=0)
S = centered.T @ centered / n # denominador ML, no n - 1
if np.linalg.slogdet(S)[0] <= 0:
raise ValueError('La covarianza muestral debe ser positiva definida')
t0 = np.r_[0.4, 0.8, 0.8, 0.8, 0.8, np.log([1., .6] + [.5]*6)]
fit = minimize(sem_objective, t0, args=(S,), jac=True, method='BFGS',
options={'gtol': 1e-7, 'maxiter': 1000})
if np.linalg.norm(fit.jac, ord=np.inf) > 1e-5:
raise RuntimeError('El optimizador no alcanzó una solución estacionaria')
return dict(params=fit.x, S=S, n=n, fit=fit)
def sem_inference(result):
n, S, t = result['n'], result['S'], result['params']
p = S.shape[0]
# Hessiano observado de -log L = n/2 * F: diferencias centradas de su gradiente.
h = 1e-4 * np.maximum(1, np.abs(t))
H = np.empty((len(t),len(t)))
for j in range(len(t)):
delta = np.zeros_like(t); delta[j] = h[j]
H[:,j] = n/2 * (sem_objective(t+delta,S)[1] - sem_objective(t-delta,S)[1])/(2*h[j])
H = (H + H.T)/2
if np.linalg.eigvalsh(H).min() <= 0:
raise RuntimeError('Hessiano no positivo: inferencia regular no disponible')
se = np.sqrt(np.diag(np.linalg.inv(H)))
logdetS = np.linalg.slogdet(S)[1]
discrepancy = max(0., sem_objective(t,S)[0] - logdetS - p)
df = p*(p+1)//2 - len(t)
stat = n * discrepancy
return dict(**result, se=se, Sigma=sem_cov(t), H=H,
chi2=stat, df=df, pvalue=gammaincc(df/2,stat/2))rng = np.random.default_rng(6408)
n = 800
xi = rng.normal(size=n)
eta = 0.65 * xi + rng.normal(scale=np.sqrt(.6), size=n)
loadings = np.array([1., .8, 1.2, 1., .7, 1.1])
errors = rng.normal(size=(n,6)) * np.sqrt([.4, .5, .6, .4, .5, .6])
observed = np.column_stack([xi]*3 + [eta]*3) * loadings + errors
out = sem_fit(observed)
out = sem_inference(out)
names = ['beta','carga2','carga3','carga5','carga6','logvar_xi','logvar_zeta'] + [f'logvar_e{i}' for i in range(1,7)]
print('convergencia: gradiente máximo =', f"{np.max(np.abs(out['fit'].jac)):.2g}")
for name, estimate, se in zip(names,out['params'],out['se']):
print(f'{name:12s} {estimate: .5f} EE {se:.5f}')
print('chi2 =', round(out['chi2'],5), 'gl =', out['df'], 'p =', round(out['pvalue'],5))
print('rango Jacobiano =', np.linalg.matrix_rank(sem_cov(out['params'],True)[1].reshape(13,-1).T))
print('mayor residuo de covarianza =', round(np.max(np.abs(out['S']-out['Sigma'])),5))Install semopy, NumPy and pandas to check estimates and fit locally on the same data. semopy’s default standard error uses expected information while the custom cell calculates observed Hessian; they need not agree in finite samples.
import numpy as np
import pandas as pd
import semopy
# Reproduce los datos de la celda Pyodide sin depender de sus variables.
rng = np.random.default_rng(6408)
n = 800
xi = rng.normal(size=n)
eta = .65 * xi + rng.normal(scale=np.sqrt(.6), size=n)
loadings = np.array([1., .8, 1.2, 1., .7, 1.1])
errors = rng.normal(size=(n,6)) * np.sqrt([.4, .5, .6, .4, .5, .6])
data = np.column_stack([xi]*3 + [eta]*3) * loadings + errors
frame = pd.DataFrame(data, columns=['x1','x2','x3','x4','x5','x6'])
description = '''
xi =~ x1 + x2 + x3
eta =~ x4 + x5 + x6
eta ~ xi
'''
model = semopy.Model(description)
fit = model.fit(frame, obj='MLW', options={'ftol': 1e-12, 'maxiter': 2000})
if not fit.success:
raise RuntimeError(fit.message)
print('semopy', semopy.__version__)
estimates = model.inspect()
stats = semopy.calc_stats(model)
print(estimates.to_string(index=False))
print(stats[['chi2','DoF','chi2 p-value']])
beta = estimates.query("lval == 'eta' and op == '~' and rval == 'xi'")['Estimate'].iloc[0]
# Valores redondeados de la celda Pyodide; las tolerancias admiten diferencias numéricas.
print('Comparación: beta propia 0.60598; semopy', round(beta,5))
print('Comparación: chi2 propio 14.52508; semopy', round(stats['chi2'].iloc[0],5))
assert abs(beta - .60598) < 1e-4
assert abs(stats['chi2'].iloc[0] - 14.52508) < 1e-3npm run lab and open the connection link.Exercises
Step 1 of 3. Which shocks make both equations hold for observed P and Q?
import numpy as np
def check_identification(B, Gamma, eq):
"""Clasifica la ecuación por orden y rango de las exclusiones."""
passThe cell checks matrices used as test references:
"""Referencias numéricas de los ejemplos de orden y rango."""
import numpy as np
singular = np.array([[1.,2.],[2.,4.]])
identified = np.array([[1.,2.],[2.,5.]])
endog_exog = np.array([[1.,1.],[.7,2.]])
print('Matriz colineal: determinante y rango:', np.linalg.det(singular), np.linalg.matrix_rank(singular))
print('Matriz perturbada: determinante y rango:', np.linalg.det(identified), np.linalg.matrix_rank(identified))
print('Exclusiones de una endógena y una exógena, determinante y rango:',
np.linalg.det(endog_exog), np.linalg.matrix_rank(endog_exog))import numpy as np
B_quiz=np.array([[1.,.2,.1],[.2,1.,.3],[.3,.1,1.]])
G_quiz=np.array([[0.,0.,1.,1.],[0.,1.,0.,0.],[1.,0.,1.,1.]])
for eq in range(3):
print('Ecuación, estado, orden y rango:',eq+1,*identification(B_quiz,G_quiz,eq))
p=8
moments=p*(p+1)//2
free=6+2+1+8
print('SEM: momentos, parámetros libres, grados de libertad:',moments,free,moments-free)
for b,d in ((1.,1.),(2.,.5)):
print('Pendientes de demanda y oferta, covarianza de shocks:',-b,d,1-b*d)