How do I detrend time series?

How do I detrend time series? Is it ok to just take first difference and run a Dickey Fuller test, and if it is stationary we are good?

I also found online that I can detrend the time series by doing this in Stata:

reg lncredit time
predict u_lncredit, residuals
twoway line u_lncredit time
dfuller u_lncredit, drift regress lags(0)


What is the best approach to detrend time series?

If the trend is deterministic (e.g. a linear trend) you could run a regression of the data on the deterministic trend (e.g. a constant plus time index) to estimate the trend and remove it from the data. If the trend is stochastic you should detrend the series by taking first differences on it.

The ADF test and the KPSS test can give you some information to determine whether the trend is deterministic or stochastic.

As the null hypothesis of the KPSS test is the opposite of the null in the
ADF test, the following way to proceed can be determined beforehand:

1. Apply the KPSS to test the null that the series is stationary or stationary
around a trend. If the null is rejected (at a predetermined level of significance) conclude that the trend is stochastic, otherwise go to step 2.
2. Apply the ADF test to test the null that a unit root exists. If the null hypothesis is rejected, then conclude that there is no unit root (stationarity), otherwise the result of the procedure is not informative since none of the tests rejected the corresponding null hypothesis. In that case it may be more cautions to consider the existence of a unit root and detrend the series by taking first differences.

In the context of structural time series models you could fit a local-level model or a local-trend model to the data to get an estimate of the trend and remove it from the series. The local-trend model is defined as follows (the local-level model is obtained with $\sigma^2_\zeta=0$):

\begin{eqnarray}
\begin{array}{rll}
\hbox{observed series:} & y_t = \mu_t + \gamma_t + \epsilon_t , &
\epsilon_t \sim \hbox{NID}(0,\, \sigma^2_\epsilon) ; \\
\hbox{latent level:} & \mu_t = \mu_{t-1} + \beta_{t-1} + \xi_t , &
\xi_t \sim \hbox{NID}(0,\, \sigma^2_\xi) ; \\
\hbox{latent drift:} & \beta_t = \beta_{t-1} + \zeta_t , &
\zeta_t \sim \hbox{NID}(0,\, \sigma^2_\zeta) ; \\
\end{array}
\end{eqnarray}