*! version 1.0.0 19aug2026

Title

xttvpivmg -- Time-varying parameter instrumental-variable mean-group
estimation of large heterogeneous panels with endogenous regressors

Syntax

xttvpivmg
depvar
[exogvars]
(endogvars = instruments)
[if] [in]
[, options]

Kernel
kernel(string) gaussian (default), epanechnikov,
rectangle or exponential

expparm(c a) parameters of the exponential kernel K(x)=exp(-c*x^a);
default 1 1

Bandwidth
h(#) second-stage bandwidth exponent: H = T^#; default 0.5

l(#) first-stage bandwidth exponent: L = T^#; default = h()

bw(#) second-stage bandwidth H directly, in periods

bwfirst(#) first-stage bandwidth L directly, in periods

cv choose (H,L) by leave-one-unit-out cross-validation

hgrid(numlist) CV grid for h; default 0.30(0.05)0.85

lgrid(numlist) CV grid for l; default 0.30(0.05)0.85

cvdivisor(string) n (default, as printed by BMK) or nminus1

nocvtrim evaluate the CV objective over all t, not the trimmed interior

Sample and model
trim(#) report t = #+1,...,T-#; default # = floor(H)

notrimming report every t, including boundary points

demean(string) none (default), fixed or tv;
see Remark 1

noconstant suppress the constant in x and z

Reporting
vce(string) paper (default, divisor N^2) or mg (divisor N(N-1))

level(#) confidence level; default level(95)

at(numlist) dates at which to tabulate the paths

tref(#) date whose estimates go into e(b)/e(V); default mid-window

summary add a summary table of the estimated paths

full also store the per-unit paths in e(bi)

Graphs
graph plot each coefficient path with its confidence band

cvplot plot the cross-validation surface (requires cv)

name(string) stub for the graph names; default tvpivmg

combine force graph combine even for a single regressor

The data must be xtset with both a panel and a time variable, and the
estimation sample must be a balanced, gap-free rectangle.

depvar, exogvars, endogvars and instruments may all contain
time-series operators.

xttvpivmg may be replayed, and supports predict.

Description

xttvpivmg implements the time-varying parameter instrumental-variable
mean-group (TVP-IV-MG) estimator of Bai, Marcellino and
Kapetanios (2026) for large heterogeneous panels in which

(a) the slope coefficients differ across units, and

(b) those coefficients change smoothly over time, and

(c) some regressors are endogenous.

The object estimated is not a scalar coefficient but a path: the
cross-sectional mean coefficient vector b0(t) = E(b_it) at every date t. The
estimator is fully non-parametric in the time dimension -- no state-space
model, no Kalman filter, no assumed break dates, no functional form for the
time variation beyond smoothness.

Mechanically it is the time-series estimator of Giraitis,
Kapetanios and Marcellino (2021) run separately on each panel unit, then averaged
across units in the manner of Pesaran and Smith (1995).
That structure is what makes inference simple: the sampling error of the kernel IV
step vanishes relative to the coefficient heterogeneity, so the standard errors are
just the cross-sectional dispersion of the N unit-level paths. There is no HAC
correction and no bootstrap.

See help xttvpivmg methods for the full
equation-by-equation derivation and the mapping from each block of code to the
paper's numbered equations.

The estimator

The model is (BMK eq. 1-2), for i = 1,...,N and t = 1,...,T:

y_it = x_it'b_it + u_it

x_it = P_it'z_it + v_it

where x_it is k x 1 (one element being a constant), z_it is p x 1 with p >= k, and
P_it is the p x k first-stage matrix. Coefficients follow the random-coefficient
decomposition b_it = b0(t) + e_it, with b0(t) a deterministic Holder-continuous
path and e_it a mean-zero, smooth, persistent random deviation.

Estimation proceeds in four steps.

1. Kernel weights (eq. 5). b_j,t(H) = K(|j-t|/H) for the second stage
and b_j,t(L) = K(|j-t|/L) for the first stage. H and L are allowed to differ and
generally should.

2. First stage (eq. 4). For each unit i and each date t, a
kernel-weighted local projection of x on z gives Phat_it.

3. Second stage (eq. 3). bhat^IV_it is a kernel-weighted IV
regression of y on x using Phat'z as the instrument block. Critically, the
first-stage matrix is evaluated at the summation index j, not at the
evaluation point t.

4. Mean group (eq. 8). bhat_MG(t) is the simple average across
units of bhat^IV_it, with variance from eq. (17).

Pointwise 95% confidence bands are bhat(t) +/- 1.96*se(bhat(t)), exactly as in the
paper's Figure 1.

Options

Kernel

kernel(string) selects the kernel K(.) in eq. (5). Allowed values are
gaussian (the default; K(x)=exp(-x^2/2)), epanechnikov
(K(x)=0.75(1-x^2)I{|x|<=1}), rectangle (also uniform;
K(x)=0.5*I{|x|<=1}) and exponential (K(x)=exp(-c*x^a)).
Multiplicative constants cancel in the estimator and have no numerical effect.

The Gaussian kernel has unbounded support: every observation contributes at
every date, with geometrically declining weight. The Epanechnikov and rectangle
kernels truncate hard at |j-t| <= H. BMK's Monte Carlo finds the Gaussian kernel
gives the lowest MAD, and it is the kernel used in their empirical application.

expparm(c a) supplies c and a for the exponential kernel. Ignored otherwise.

Bandwidth

h(#) and l(#) set the bandwidths through the exponent parameterisation
H = T^h, L = T^l used throughout the literature. h(0.5) reproduces the
rule-of-thumb H = sqrt(T) recommended by Giraitis, Kapetanios and Yates (2018) and
used as the benchmark in BMK's Monte Carlo. If l() is omitted it defaults to
h(), giving the paper's H = L = T^0.5 rule of thumb.

bw(#) and bwfirst(#) set H and L directly in periods instead. The
corresponding exponents are reported.

cv selects (H,L) jointly by the leave-one-unit-out cross-validation of BMK
section 2.3. This is a two-dimensional search: H and L are chosen
independently, and in the paper's own application they came out very different
(H = T^0.65, L = T^0.30). See Bandwidth selection below.

hgrid(numlist) and lgrid(numlist) give the search grids in exponent
units. The default 0.30(0.05)0.85 is the grid of BMK's empirical application;
their Monte Carlo used the coarser 0.3(0.1)0.7.

cvdivisor(string) controls the leave-one-out average. BMK print
bhat^{-i}(t) = (1/N)*sum_{j!=i} bhat_j(t), i.e. divisor
n -- the default here, for faithfulness. The usual convention (and
that of Sun, Carroll and Li 2009, from which the procedure is adapted) is divisor
nminus1. The choice shifts the CV objective but rarely the selected
bandwidth; try both if the selection sits on a grid boundary.

nocvtrim evaluates the CV objective over all t rather than the trimmed
interior. BMK write the objective as a sum over t = 1,...,T but evaluate all their
reported statistics on the trimmed window. Trimming the CV as well (the default
here) prevents boundary bias from driving the bandwidth choice.

Sample and model

trim(#) and notrimming control the reported window. Theorem 1(ii) of
BMK is an interior-point result: at dates near 1 or T the kernel is
one-sided and the estimates are biased. The default reports
t = floor(H)+1,...,T-floor(H), matching the window over which BMK compute MAD and
coverage. notrimming reports everything, boundary included -- useful
for diagnostics, not for inference.

demean(string) implements BMK Remark 1. none (default) is Remark 1(a):
the constant sits in x and its coefficient is itself a time-varying fixed effect.
fixed is Remark 1(b) with a time-invariant effect: y and x are residualised
on a unit-specific constant. tv is Remark 1(b) with a time-varying effect:
the residualisation is itself kernel-smoothed at bandwidth L. Both non-default
choices remove the intercept, so noconstant is imposed automatically.

noconstant omits the constant from both x and z. The model in eq. (1)
explicitly includes a constant among the regressors, so this is rarely what you
want unless you are also demeaning.

Reporting

vce(string) selects the variance divisor. paper (default) is eq. (17)
exactly: Sigmahat_e(t) uses divisor N and Var(bhat_MG(t)) = Sigmahat_e(t)/N, so
the effective divisor is N^2. mg uses the conventional Pesaran-Smith
mean-group divisor N(N-1), which is slightly larger and more conservative in small
N. The difference is a factor (N-1)/N in the variance; with N = 19 that is about
2.7% in the standard error.

at(numlist) tabulates the paths at the given dates (in timevar units)
instead of at nine evenly spaced points. Every requested date must lie inside the
reported window.

tref(#) chooses which date's estimates are posted to e(b) and
e(V), so that test, lincom and nlcom operate at that
date. The default is the middle of the reported window.

summary adds a table giving, for each regressor, the mean, minimum, maximum
and standard deviation of the estimated path plus the share of dates at which it is
significant at 5%. This is descriptive: BMK provide no inference for
time-averaged coefficients, and none is invented here.

full additionally stores the N per-unit paths in e(bi), stacked
unit-major over the reported window. Skipped with a note if N times the number of
reported dates exceeds 10,000 rows.

Graphs

graph draws one panel per regressor: the point estimate as a solid line, the
pointwise confidence band as a shaded area, and a zero reference line. Panels are
combined into a single figure in the style of BMK Figure 1. name(string)
sets the name stub; individual panels are stub_1, stub_2,
... and the combined figure is stub.

cvplot draws the cross-validation surface over the (h,l) grid, with marker
size inversely proportional to the CV objective. Requires cv.

Bandwidth selection

The bandwidth is the one genuinely consequential tuning choice, and BMK's Monte
Carlo is unambiguous that cross-validation beats the rule of thumb: with the
Gaussian kernel at N=50, T=500 the CV estimator of the autoregressive coefficient
has average MAD 0.039 against 0.069, and coverage 0.823 against 0.574.

Three practical points.

1. T must grow faster than N. Pointwise asymptotic normality requires
(H/T)^g2 = o(N^^(-1/2)), so sqrt(N)/T^^(g2(1-h)) must go to zero. In BMK's
simulations coverage improves with T but deteriorates with N for fixed T --
at N=50, T=100 the rule-of-thumb coverage for the AR coefficient falls to 0.496.
If your N is comparable to your T, treat the confidence bands with suspicion.

2. CV is expensive. Estimation is O(N*T^2) per (H,L) pair, and the default
grid has 144 pairs. The implementation reuses the first stage across the h-grid, so
the cost is roughly (number of l values) first-stage passes plus 144 second-stage
passes, but on a large panel this is still minutes rather than seconds.

3. The selected pair may violate Assumption 2.6. BMK's Assumption 2.6
requires H = o(L/(log T)^^max(1,2/a)), i.e. H of smaller order than L. Yet
the CV in their own empirical application selects H = T^0.65 and L = T^0.30, which
is the opposite ordering. This is a genuine and unresolved tension in the paper.
xttvpivmg does not constrain the grid to hide it: if CV selects h > l, that
is reported as-is and you should say so in your write-up.

Interpreting the output

The header reports N, T, the kernel, both bandwidths in periods and in
exponent form, how they were chosen, the variance convention, and the trimming
window.

The coefficient blocks. One block per regressor, with rows for the tabulated
dates. Within a block:

Coef. bhat_MG(t), the cross-sectional mean coefficient at date t (eq. 8)

Std. Err. sqrt(Sigmahat_e(t)[j,j]/N) from eq. (17)

z Coef./Std. Err.; asymptotically standard normal by Theorem 1(ii)

P>|z| two-sided pointwise p-value

Conf. Int. pointwise interval, not a uniform band

Read the path, not the rows. A single date's coefficient is rarely the object
of interest. What the estimator is for is the shape: when a coefficient
becomes significant, whether it is trending, whether it turns. Use graph.

"Pointwise" is a real caveat. Each interval covers b0(t) with probability
1-alpha at that single t. The probability that the band covers the whole path
simultaneously is much lower. BMK provide no uniform band, so do not describe the
shaded region as one.

Standard errors measure heterogeneity, not fit. Because the asymptotic
expansion collapses to (1/sqrt(N))*sum_i e_it, the standard error at date t is
driven entirely by how much the N unit-level estimates disagree at t. A tight band
means the units agree; it does not mean each unit's regression fits well.

Remarks and practical guidance

Which regressors go in the parentheses. Everything inside is projected through
the first stage; everything outside instruments itself. In BMK's own empirical
application all four regressors (constant, lagged inflation, unemployment and
lead inflation) are treated as endogenous with respect to a separate instrument
set, so they all go inside. Putting a genuinely exogenous regressor inside is not
an error -- it is projected on a set containing itself, which returns it
-- but it wastes computation.

Dynamic panels are allowed. BMK Remark 4 licenses a lagged dependent variable
as a weakly exogenous regressor, citing Hsiao, Pesaran and Tahmiscioglu (1999);
their own Monte Carlo and application both include one. Write it as
L.depvar in exogvars or inside the parentheses as you prefer.

Correlated random coefficients are fine. Unusually for a mean-group
estimator, consistency does not require E(e_i|x_it) = 0. The smoothness
condition on e_it does the work instead, so the estimator survives correlated
random coefficients -- a case in which the standard MG estimator is
inconsistent. BMK's Monte Carlo deliberately builds this in.

It is a smoother, not a filter. The kernel is two-sided: bhat(t) uses
observations both before and after t. These are not real-time estimates and must
not be interpreted as what an agent could have known at t.

Sample-size regime. BMK simulate N in {10,20,50} and T in
{100,200,500}. Outside that region, and especially when N approaches
or exceeds T, the pointwise normal approximation degrades in a direction that
understates uncertainty.

Singular systems. If the second-stage k x k matrix is singular for some
unit-date pair, that unit is dropped from the mean-group average at that date and
the number of such drops is reported. A large count usually means weak instruments
locally, too small an H, or a near-collinear regressor set.

Validating against an independent implementation. The per-unit paths are
exactly the time-series estimator of Giraitis, Kapetanios and Marcellino (2021).
The gretl package ketvals (Valentini and Lucchetti) implements that estimator
independently; running its tv_IV on each unit and averaging the N paths by
hand reproduces e(bmg). Note that ketvals reports the time-series
sandwich variance, which is a different object from eq. (17) and will not match
e(semg).

Limitations

These are properties of the method, not of the implementation, and are stated here
rather than papered over.

No cross-sectional dependence. Assumption 2.2 requires regressors, errors and
random coefficients to be independent across units. There is no common-factor or
CCE variant of this estimator. If your panel has strong CSD, the mean-group
variance in eq. (17) is not valid. Test for it first (xtcd2, or
xttestpanel if installed).

No test of parameter constancy. BMK provide no test of H0: b0(t) = b0. The
visual evidence from graph is not a test, and none is supplied here.

No uniform confidence band. Pointwise only.

No weak-instrument diagnostic. The paper offers none for the time-varying
case. Per-period Hausman and Sargan statistics do exist in Giraitis,
Kapetanios and Marcellino (2021) for the time-series case, but they are not part
of BMK and are not implemented here.

Balanced panels only. The kernel sums run over j = 1,...,T and assume a
complete regular rectangle. Use tsfill or drop short units.

Examples

Setup

. webuse grunfeld, clear

. xtset company year

Rule of thumb H = L = T^0.5, one endogenous regressor

. xttvpivmg invest kstock (mvalue = L.mvalue L2.mvalue)

Same, with the coefficient paths plotted

. xttvpivmg invest kstock (mvalue = L.mvalue L2.mvalue), graph

Different bandwidths for the two stages

. xttvpivmg invest kstock (mvalue = L.mvalue L2.mvalue), h(0.65) l(0.30)

Data-driven bandwidths by leave-one-unit-out cross-validation

. xttvpivmg invest kstock (mvalue = L.mvalue L2.mvalue), cv graph cvplot

The hybrid Phillips curve of BMK section 4

. xtset country month

. xttvpivmg inf (L.inf urate F.inf = L2.inf L3.inf L4.inf L.urate L2.urate), ///

cv kernel(gaussian) graph summary

Note that all three substantive regressors sit inside the parentheses, because in
BMK's specification lead inflation is endogenous by construction and the remaining
regressors are instrumented by their own further lags.

Epanechnikov kernel, no trimming, conservative variance

. xttvpivmg y x1 (x2 = z1 z2), kernel(epan) notrimming vce(mg)

Tabulate at chosen dates and post that date to e(b)

. xttvpivmg y x1 (x2 = z1 z2), at(1995 2000 2005 2010) tref(2005)

. test x1

Time-varying fixed effects (Remark 1(b))

. xttvpivmg y x1 (x2 = z1 z2), demean(tv) l(0.4)

Recover the paths for your own graph or table

. matrix B = e(bmg)

. matrix S = e(semg)

. matrix D = e(tlist)

A complete, self-contained demonstration that simulates BMK's own Monte Carlo
design and checks that the estimator recovers the true coefficient paths is
supplied in xttvpivmg_example.do. Retrieve it with
net get xttvpivmg and run it with do xttvpivmg_example.do.

Stored results

xttvpivmg stores the following in e():

Scalars

e(N) number of observations

e(N_g) number of panel units, N

e(T) number of time periods, T

e(k_x) number of regressors k (including the constant)

e(p_z) number of instruments p (including the constant)

e(H) second-stage bandwidth in periods

e(L) first-stage bandwidth in periods

e(hexp) h such that H = T^h

e(lexp) l such that L = T^l

e(trim) number of dates trimmed at each end

e(nrep) number of dates reported

e(tref) date posted to e(b)/e(V)

e(nsing) number of singular unit-date systems dropped

e(cvmin) minimised CV objective (with cv)

e(level) confidence level

Macros

e(cmd) xttvpivmg

e(cmdline) command as typed

e(depvar) name of dependent variable

e(exogvars) included exogenous regressors

e(endogvars) endogenous regressors

e(insts) excluded instruments

e(xnames) column names of e(bmg)

e(znames) full instrument list

e(ivar) panel variable

e(tvar) time variable

e(kernel) kernel used

e(bwsel) how the bandwidths were chosen

e(vcetype) paper or mg

e(demean) none, fixed or tv

e(predict) xttvpivmg_p

Matrices

e(b) coefficients at e(tref)

e(V) (diagonal) variance at e(tref)

e(bmg) nrep x k matrix of mean-group coefficient paths

e(semg) nrep x k matrix of standard errors

e(tlist) nrep x 1 vector of dates, aligned with the rows above

e(bi) (N*nrep) x k per-unit paths, unit-major (with full)

e(cvobj) CV objective at each grid point (with cv)

e(cvgrid) the (h,l) grid, aligned with e(cvobj) (with cv)

Functions

e(sample) marks estimation sample

e(b) and e(V) hold a single date so that test and
lincom work; the paths in e(bmg) are the estimator's actual output.

References

Bai, Y., M. Marcellino and G. Kapetanios. 2026. Mean group instrumental variable
estimation of time-varying large heterogeneous panels with endogenous regressors.
Econometrics and Statistics 37: 26-41.
doi:10.1016/j.ecosta.2023.06.004

Giraitis, L., G. Kapetanios and M. Marcellino. 2021. Time-varying instrumental
variable estimation. Journal of Econometrics 224(2): 394-415.
doi:10.1016/j.jeconom.2020.08.013

Giraitis, L., G. Kapetanios and T. Yates. 2014. Inference on stochastic
time-varying coefficient models. Journal of Econometrics 179(1): 46-65.

Giraitis, L., G. Kapetanios and T. Yates. 2018. Inference on multivariate
heteroscedastic time varying random coefficient models. Journal of Time Series
Analysis 39(2): 129-149.

Dendramis, Y., L. Giraitis and G. Kapetanios. 2021. Estimation of time-varying
covariance matrices for large datasets. Econometric Theory 37(6): 1100-1134.

Lucchetti, R. and F. Valentini. 2023. Kernel-based time-varying IV estimation:
handle with care. Empirical Economics 65(6): 3001-3026.
doi:10.1007/s00181-023-02450-6

Pesaran, M. H. and R. Smith. 1995. Estimating long-run relationships from dynamic
heterogeneous panels. Journal of Econometrics 68(1): 79-113.
doi:10.1016/0304-4076(94)01644-F

Hsiao, C. and M. H. Pesaran. 2008. Random coefficient models. In The
Econometrics of Panel Data, ed. L. Matyas and P. Sevestre, 185-213. Berlin:
Springer.

Sun, Y., R. J. Carroll and D. Li. 2009. Semiparametric estimation of fixed-effects
panel data varying coefficient models. Advances in Econometrics 25: 101-129.
doi:10.1108/S0731-9053(2009)0000025006

Gali, J. and M. Gertler. 1999. Inflation dynamics: A structural econometric
analysis. Journal of Monetary Economics 44(2): 195-222.

Author

Dr Merwan Roudane

merwanroudane920@gmail.com

https://github.com/merwanroudane

Bug reports and suggestions are welcome.

Also see

Manual: xtset, ivregress, tsfill

Online: xttvpivmg methods,
xttvpivmg postestimation