How many lags to use in the Ljung-Box test of a time series? After an ARMA model is fit to a time series, it is common to check the residuals via the Ljung-Box portmanteau test (among other tests).  The Ljung-Box test returns a p value.  It has a parameter, h, which is the number of lags to be tested.  Some texts recommend using h=20; others recommend using h=ln(n); most do not say what h to use.
Rather than using a single value for h, suppose that I do the Ljung-Box test for all h<50, and then pick the h which gives the minimum p value.  Is that approach reasonable?  What are the advantages and disadvantages?  (One obvious disadvantage is increased computation time, but that is not a problem here.)  Is there literature on this?
To elaborate slightly....  If the test gives p>0.05 for all h, then obviously the time series (residuals) pass the test.  My question concerns how to interpret the test if p<0.05 for some values of h and not for other values.
 A: Before you zero-in on the "right" h (which appears to be more of an opinion than a hard rule), make sure the "lag" is correctly defined.
http://www.stat.pitt.edu/stoffer/tsa2/Rissues.htm
Quoting the section below Issue 4 in the above link:
"....The p-values shown for the Ljung-Box statistic plot are incorrect because the degrees of freedom used to calculate the p-values are lag instead of lag - (p+q). That is, the procedure being used does NOT take into account the fact that the residuals are from a fitted model. And YES, at least one R core developer knows this...."
Edit (01/23/2011): Here's an article by Burns that might help:
http://lib.stat.cmu.edu/S/Spoetry/Working/ljungbox.pdf
A: The thread "Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey" shows that the Ljung-Box test is essentially inapplicable in the case of an autoregressive model. It also shows that Breusch-Godfrey test should be used instead. That limits the relevance of your question and the answers (although the answers may include some generally good points). 
A: The two most common settings are $\min(20,T-1)$ and $\ln T$ where $T$ is the length of the series, as you correctly noted.
The first one is supposed to be from the authorative book by Box, Jenkins, and Reinsel. Time Series Analysis: Forecasting and Control. 3rd ed. Englewood Cliffs, NJ: Prentice Hall, 1994.. However, here's all they say about the lags on p.314:

It's not a strong argument or suggestion by any means, yet people keep repeating it from one place to another.
The second setting for a lag is from Tsay, R. S. Analysis of Financial Time Series. 2nd Ed. Hoboken, NJ: John Wiley & Sons, Inc., 2005, here's what he wrote on p.33:

Several values of m are often used. Simulation studies suggest that
  the choice of m ≈ ln(T ) provides better power performance. 

This is a somewhat stronger argument, but there's no description of what kind of study was done. So, I wouldn't take it at a face value. He also warns about seasonality:

This
  general rule needs modification in analysis of seasonal time series
  for which autocorrelations with lags at multiples of the seasonality
  are more important.

Summarizing, if you just need to plug some lag into the test and move on, then you can use either of these setting, and that's fine, because that's what most practitioners do. We're either lazy or, more likely, don't have time for this stuff. Otherwise, you'd have to conduct your own research on the power and properties of the statistics for series that you deal with.
UPDATE.
Here's my answer to Richard Hardy's comment and his answer, which refers to another thread on CV started by him. You can see that the exposition in the accepted (by Richerd Hardy himself) answer in that thread is clearly based on ARMAX model, i.e. the model with exogenous regressors $x_t$:$$y_t = \mathbf x_t'\beta + \phi(L)y_t + u_t$$
However, OP did not indicate that he's doing ARMAX, to contrary, he explicitly mentions ARMA:

After an ARMA model is fit to a time series, it is common to check the
  residuals via the Ljung-Box portmanteau test

One of the first papers that pointed to a potential issue with LB test was Dezhbaksh, Hashem (1990). “The Inappropriate Use of Serial Correlation Tests in Dynamic Linear Models,” Review of Economics and Statistics, 72, 126–132. Here's the excerpt from the paper:

As you can see, he doesn't object to using LB test for pure time series models such as ARMA. See also the discussion in the manual to a standard econometrics tool EViews:

If the series represents the residuals from ARIMA estimation, the
  appropriate degrees of freedom should be adjusted to represent the
  number of autocorrelations less the number of AR and MA terms
  previously estimated. Note also that some care should be taken in
  interpreting the results of a Ljung-Box test applied to the residuals
  from an ARMAX specification (see Dezhbaksh, 1990, for simulation
  evidence on the finite sample performance of the test in this setting)

Yes, you have to be careful with ARMAX models and LB test, but you can't make a blanket statement that LB test is always wrong for all autoregressive series.
UPDATE 2
Alecos Papadopoulos's answer shows why Ljung-Box test requires strict exogeneity assumption. He doesn't show it in his post, but Breusch-Gpdfrey test (another alternative test) requires only weak exogeneity, which is better, of course. This what Greene, Econometrics, 7th ed. says on the differences between tests, p.923:

The essential difference between the Godfrey–Breusch and the
  Box–Pierce tests is the use of partial correlations (controlling for X
  and the other variables) in the former and simple correlations in the
  latter. Under the null hypothesis, there is no autocorrelation in εt ,
  and no correlation between $x_t$ and $\varepsilon_s$ in any event, so the two tests
  are asymptotically equivalent. On the other hand, because it does not
  condition on $x_t$ , the Box–Pierce test is less powerful than the LM
  test when the null hypothesis is false, as intuition might suggest.

A: Assume that we specify a simple AR(1) model, with all the usual properties,
$$y_t = \beta y_{t-1} + u_t$$
Denote the theoretical covariance of the error term as
$$\gamma_j \equiv E(u_tu_{t-j})$$
If we could observe the error term, then the sample autocorrelation of the error term is defined as
$$\tilde \rho_j \equiv \frac {\tilde \gamma_j}{\tilde \gamma_0}$$
where
$$\tilde\gamma_j  \equiv \frac 1n \sum_{t=j+1}^nu_tu_{t-j},\;\;\; j=0,1,2...$$
But in practice, we do not observe the error term. So the sample autocorrelation related to the error term will be estimated using the residuals from estimation, as
$$\hat\gamma_j  \equiv \frac 1n \sum_{t=j+1}^n\hat u_t\hat u_{t-j},\;\;\; j=0,1,2...$$
The Box-Pierce Q-statistic (the Ljung-Box Q is just an asymptotically neutral scaled version of it) is
$$Q_{BP} = n \sum_{j=1}^p\hat\rho^2_j = \sum_{j=1}^p[\sqrt n\hat\rho_j]^2\xrightarrow{d}  \;???\;\chi^2(p) $$
Our issue is exactly whether $Q_{BP}$ can be said to have asymptotically a chi-square distribution (under the null of no-autocorellation in the error term) in this model.
For this to happen, each and everyone of $\sqrt n \hat\rho_j$ must be asymptotically standard Normal. A way to check this is to examine whether $\sqrt n \hat\rho$ has the same asymptotic distribution as $\sqrt n \tilde\rho$ (which is constructed using the true errors, and so has the desired asymptotic behavior under the null).
We have that
$$\hat u_t = y_t - \hat \beta y_{t-1} = u_t - (\hat \beta -  \beta)y_{t-1}$$
where $\hat \beta$ is a consistent estimator. So
$$\hat\gamma_j  \equiv \frac 1n \sum_{t=j+1}^n[u_t - (\hat \beta -  \beta)y_{t-1}][u_{t-j} - (\hat \beta -  \beta)y_{t-j-1}]$$
$$=\tilde \gamma _j -\frac 1n \sum_{t=j+1}^n (\hat \beta - \beta)\big[u_ty_{t-j-1} +u_{t-j}y_{t-1}\big] + \frac 1n \sum_{t=j+1}^n(\hat \beta -  \beta)^2y_{t-1}y_{t-j-1}$$
The sample is assumed to be stationary and ergodic, and moments are assumed to exist up until the desired order. Since the estimator $\hat \beta$ is consistent, this is enough for the two sums to go to zero. So we conclude
$$\hat \gamma_j \xrightarrow{p} \tilde \gamma_j$$
This implies that
$$\hat \rho_j \xrightarrow{p} \tilde \rho_j \xrightarrow{p} \rho_j$$
But this does not automatically guarantee that $\sqrt n \hat \rho_j$ converges to  $\sqrt n\tilde \rho_j$ (in distribution) (think that the continuous mapping theorem does not apply here because the transformation applied to the random variables depends on $n$). In order for this to happen, we need
$$\sqrt n \hat \gamma_j \xrightarrow{d} \sqrt n \tilde \gamma_j$$
(the denominator $\gamma_0$ -tilde or hat- will converge to the variance of the error term in both cases, so it is neutral to our issue).
We have
$$\sqrt n \hat \gamma_j =\sqrt n\tilde \gamma _j -\frac 1n \sum_{t=j+1}^n \sqrt n(\hat \beta - \beta)\big[u_ty_{t-j-1} +u_{t-j}y_{t-1}\big] \\+ \frac 1n \sum_{t=j+1}^n\sqrt n(\hat \beta -  \beta)^2y_{t-1}y_{t-j-1}$$
So the question is : do these two sums, multiplied now by $\sqrt n$, go to zero in probability so that we will be left with $\sqrt n \hat \gamma_j =\sqrt n\tilde \gamma _j$ asymptotically?
For the second sum we have
$$\frac 1n \sum_{t=j+1}^n\sqrt n(\hat \beta -  \beta)^2y_{t-1}y_{t-j-1} = \frac 1n \sum_{t=j+1}^n\big[\sqrt n(\hat \beta -  \beta)][(\hat \beta -  \beta)y_{t-1}y_{t-j-1}]$$
Since $[\sqrt n(\hat \beta -  \beta)]$ converges to a random variable, and $\hat \beta$ is consistent, this will go to zero.
For the first sum, here too we have that $[\sqrt n(\hat \beta -  \beta)]$ converges to a random variable, and so we have that
$$\frac 1n \sum_{t=j+1}^n \big[u_ty_{t-j-1} +u_{t-j}y_{t-1}\big] \xrightarrow{p} E[u_ty_{t-j-1}] + E[u_{t-j}y_{t-1}]$$
The first expected value, $E[u_ty_{t-j-1}]$ is zero by the assumptions of the standard AR(1) model. But the second expected value is not, since the dependent variable depends on past errors.
So $\sqrt n\hat \rho_j$ won't have the same asymptotic distribution as $\sqrt n\tilde \rho_j$. But the asymptotic distribution of the latter is standard Normal, which is the one leading to a chi-squared distribution when squaring the r.v.
Therefore we conclude, that in a pure time series model, the Box-Pierce Q and the Ljung-Box Q statistic cannot be said to have an asymptotic chi-square distribution, so the test loses its asymptotic justification.
This happens because the right-hand side variable (here the lag of the dependent variable) by design is not strictly exogenous to the error term, and we have found that such strict exogeneity is required for the BP/LB Q-statistic to have the postulated asymptotic distribution.
Here the right-hand-side variable is only "predetermined", and the Breusch-Godfrey test is then valid. (for the full set of conditions required for an asymptotically valid test, see Hayashi 2000, p. 146-149).
A: The answer definitely depends on: 
What are actually trying to use the $Q$ test for? 
The common reason is: to be more or less confident about joint statistical significance of the null hypothesis of no autocorrelation up to lag $h$ (alternatively assuming that you have something close to a weak white noise) and to build a parsimonious model, having as little number of parameters as possible.
Usually time series data has natural seasonal pattern, so the practical rule-of-thumb would be to set $h$ to twice this value. Another one is the forecasting horizon, if you use the model for forecasting needs. Finally if you find some significant departures at latter lags try to think about the corrections (could this be due to some seasonal effects, or the data was not corrected for outliers).

Rather than using a single value for h, suppose that I do the Ljung-Box test for all h<50, and then pick the h which gives the minimum p value.

It's a joint significance test, so if the choice of $h$ is data-driven, then why should I care about some small (occasional?) departures at any lag less than $h$, supposing that it is much less than $n$ of course (the power of the test you mentioned). Seeking to find a simple yet relevant model I suggest the information criteria as described below.

My question concerns how to interpret the test if $p<0.05$ for some values of $h$ and not for other values.

So it will depend on how far from the present it happens. Disadvantages of far departures: more parameters to estimate, less degrees of freedom, worse predictive power of the model.
Try to estimate the model including the MA and\or AR parts at the lag where the departure occurs AND additionally look at one of information criteria (either AIC or BIC depending on the sample size) this would bring you more insights on what model is more parsimonious. Any out-of-sample prediction exercises are also welcome here.
A: Escanciano and Lobato constructed a portmanteau test with automatic, data-driven lag selection  based on the Pierce-Box test and its refinements (which include the Ljung-Box test). 
The gist of their approach is to combine the AIC and BIC criteria --- common in the identification and estimation of ARMA models --- to select the optimal number of lags to be used. In the introduction of they suggest that, intuitively, ``test conducted using the BIC criterion are able to properly control for type I error and are more powerful when serial correlation is present in the first order''. Instead, tests based on AIC are more powerful against high order serial correlation. Their procedure thus choses a BIC-type lag selection in the case that autocorrelations seem to be small and present only at low order, and an AIC-type lag section otherwise. 
The test is implemented in the R package vrtest (see function Auto.Q).
A: ... h should be as small as possible to preserve whatever power the LB test may have under the circumstances. As h increases the power drops.  The LB test is a dreadfully weak test; you must have a lot of samples; n must be ~> 100 to be meaningful. Unfortunately I have never
seen a better test.  But perhaps one exists.  Anyone know of one ?
Paul3nt 
A: There's no correct answer to this that works in all situation for the reasons other have said it will depend on your data. 
That said, after trying to figure out to reproduce a result in Stata in R I can tell you that, by default Stata implementation uses: $\mathrm{min}(\frac{n}{2}-2, 40)$. Either half the number of data points minus 2, or 40, whichever is smaller.
All defaults are wrong, of course, and this will definitely be wrong in some situations. In many situations, this might not be a bad place to start.
A: Let me suggest you our R package hwwntest. It has implemented Wavelet-based white noise tests that do not require any tuning parameters and have good statistical size and power.
Additionally, I have recently found "Thoughts on the Ljung-Box test" which is excellent discussion on the topic from Rob Hyndman.
Update: Considering the alternative discussion in this thread regarding ARMAX, another incentive to look at hwwntest is the availability of a theoretical power function for one of the tests against an alternative hypothesis of ARMA(p,q) model. 
