Spectral analysis and long memory
View the same series in frequency: spectral density distributes variance across cycles. Study Herglotz's spectral representation, Wold decomposition, the periodogram and its inconsistency, smoothed Welch and multitaper estimators, linear filters through frequency response, and long-memory processes such as ARFIMA and the Hurst exponent, whose ACF decays as a power.
After this lesson you can
- Calculate spectral density for ARMA and filtered processes and read cycles and persistence from it.
- Prove periodogram inconsistency and construct consistent Welch and multitaper estimators.
- Design and interpret filters through frequency response, including the spurious cycle created by moving averages.
- Estimate long-memory parameters with GPH and R/S analysis and compare them.
- State the Wold decomposition and explain what it says about the universality of linear models.
Before you start
- 26Autocovariance functionARMA modelLinear processSample ACF and Bartlett's formulaMoving average filtersIntegrated process
- 03Fourier seriesFourier transformParseval and Plancherel identities
- 09Discrete Fourier transform and FFTSampling and aliasing
- 04Exponential, gamma and chi-squared distributions
- 02Symmetric generalized eigenvalue problem
A second way to view dependence
A series can contain a weekly oscillation, slow variation and fast noise at the same time. Autocovariance compares lags; the spectrum distributes variance over frequencies. These are related views of the same second-order structure, not two independent proofs that a cycle has a physical cause.
Place poles and zeros and observe which frequencies the filter amplifies. A pole close to the unit circle can produce a narrow peak, but the exact maximum of a second-order AR need not coincide with the pole angle.
Variance distributed over frequency
For a real centered weakly stationary process, a spectral density is normalized here per radian:
when the autocovariance series is absolutely summable. Thus . For white noise with variance , . Angular frequency is in radians per sample; is in cycles per sample and a nonzero cycle has period samples. Changing units also changes density: per cycle, .
The Herglotz spectral representation is more general: a nonnegative-definite autocovariance function corresponds to a finite nonnegative measure on the circle, with
The measure is symmetric for a real series. It can contain atoms or a singular part and therefore need not have a density with respect to Lebesgue measure. For example, a random-phase sinusoid can contribute point mass. The process representation in uses orthogonal spectral increments; orthogonality does not imply independence without further assumptions such as joint Gaussianity.
The predictable part and innovation
The Wold decomposition writes a centered second-order stationary process as
Innovations are uncorrelated, is orthogonal to them and represents the linearly deterministic part from the infinite past. If the process is purely nondeterministic, . The innovation is the error of the best linear projection on the past; it need not be independent or equal the error relative to all nonlinear information. Wold does not claim every dynamic is a finite ARMA: the representation can require infinitely many coefficients.
Filters, poles and induced cycles
A stable linear filter with absolutely summable coefficients has response and density
For a causal ARMA with innovation variance and polynomials from the previous lesson,
Poles near the unit circle raise the response near their angles and zeros attenuate it. The maximum of the full ratio depends on all factors: a pole’s angle is not always the exact peak. In an AR(2) with inverse roots and white noise, if the maximum is interior,
If the right-hand side lies outside , the maximum is at an endpoint of . This distinction matters even when is close to one.
The Slutsky effect shows that filtering noise can create apparently regular oscillations. Composing sums and differences changes : the filter can suppress low and high frequencies simultaneously, leaving an intermediate band. The resulting signal has spectral structure created by the procedure; it does not prove an external clock exists in the original generator.
Why the raw periodogram does not stabilize
The periodogram of , under the preceding convention, is
For iid Gaussian noise with variance , at interior Fourier frequencies other than zero or Nyquist, is exponential with mean one. At those frequencies its variance is for every : adding data does not reduce relative variability of an individual ordinate. Zero and Nyquist endpoints have another distribution; estimated mean and frequency choice also matter.
To see the expectation, expand the squared modulus and group the pairs with lag :
If , dominated convergence gives . Also, for a causal linear process with absolutely summable coefficients and iid innovations with finite fourth moment, at Fourier frequencies converging to an interior frequency with , the DFT central limit theorem gives two asymptotically independent Gaussian components and . Ratio converges in distribution to a nondegenerate exponential, so it does not converge in probability to one: the periodogram is not pointwise consistent. A rectangular window convolves the true spectrum with a Fejér kernel. A peak between Fourier frequencies spreads energy across ordinates: spectral leakage, not necessarily multiple cycles.
Smooth without erasing the phenomenon
Smoothed spectral estimation reduces variance by combining nearby frequency information. Welch divides the series into segments, windows each and averages their periodograms. Normalization must account for window energy and whether the spectrum is two-sided or one-sided. Shorter segments yield more averages but widen peaks and reduce resolution; overlap makes averages dependent. Welch describes the original method.
Multitaper uses several orthogonal windows on the same series and averages their estimates. Thomson’s DPSS concentrate energy in a chosen band; the time-bandwidth product and number of tapers control resolution and variance. Orthogonal sinusoidal tapers also exist and differ from DPSS. Do not call an average of arbitrary windows DPSS. See Thomson.
For consistency, increasing with a fixed number of segments or tapers is insufficient. In an appropriate regime, segment length and the number of averages must grow while the effective smoothing band narrows; for multitaper, a typical formulation makes and . Regularity and dependence control are also required. A peak may blur or merge with a broad band: choose resolution and variance according to the question, not merely a smoother curve.
Long memory versus persistence
Second-order long memory appears, for example, in ARFIMA for :
The fractional operator is defined by its binomial series and requires convergence control. Near zero grows as but remains integrable for . ACF decays as a power with exponent and is not absolutely summable. By contrast, for a causal AR(1) with fixed coefficient, ACF decays geometrically. In ARFIMA with , mean variance asymptotically decays as a constant times , slower than .
The GPH estimator regresses the low-frequency log-periodogram on ; its slope estimates . Exclude frequency zero and choose how many low frequencies to use: too many introduce short-run bias, too few increase variance. R/S studies the rescaled cumulative range; DFA removes a local trend from the accumulated series and observes fluctuation growth with scale. In the standard stationary fractional model, the associated asymptotic exponent is , but finite estimates can differ greatly and an estimate of alone does not identify the model.
A level shift, trend or changing variance can imitate low-frequency persistence. Before attributing a result to long memory, compare with break models and check sensitivity to window, preprocessing and scales. Hosking develops fractional differencing.
Lab: FFT, Welch and multitaper
The code uses two-sided normalization in cycles per sample: for white noise of variance one the density is one. In the one-sided representation, interior frequencies are doubled, but zero and Nyquist are not. Each executable cell retains variables from earlier cells.
import numpy as np
from scipy import signal
from scipy.signal.windows import dpss
def unilateral(p, n):
p = p.copy()
if n % 2 == 0:
p[1:-1] *= 2
else:
p[1:] *= 2
return p
def periodograma(x):
x = np.asarray(x, dtype=float)
n = len(x)
return np.fft.rfftfreq(n), unilateral(abs(np.fft.rfft(x))**2/n, n)
def welch_propio(x, largo, solape):
x = np.asarray(x, dtype=float)
if not 0 <= solape < largo <= len(x):
raise ValueError("segmento o solape inválido")
ventana = signal.windows.hann(largo, sym=False)
energia = ventana@ventana
espectros = []
for inicio in range(0, len(x)-largo+1, largo-solape):
z = x[inicio:inicio+largo]*ventana
espectros.append(unilateral(abs(np.fft.rfft(z))**2/energia, largo))
return np.fft.rfftfreq(largo), np.mean(espectros, axis=0)
rng = np.random.default_rng(1414)
x = rng.normal(size=2048)
f, p = periodograma(x)
f_ref, p_ref = signal.periodogram(x, fs=1., detrend=False, scaling="density")
fw, pw = welch_propio(x, 256, 128)
fw_ref, pw_ref = signal.welch(x, fs=1., window="hann", nperseg=256,
noverlap=128, detrend=False, scaling="density")
print("errores periodograma y Welch frente a scipy:",
np.max(abs(p-p_ref)), np.max(abs(pw-pw_ref)))
print("segundo momento muestral y potencia unilateral integrada:",
np.mean(x*x), np.sum(p)/len(x))The discrete area of the one-sided spectrum uses spacing . The next cell calculates a real multitaper average using DPSS and compares its variability with a single periodogram. It does not assume exact independence of tapers for every process or turn an average’s distribution into a universal band.
def multitaper(x, ancho=3., cantidad=5):
x = np.asarray(x, dtype=float)
ventanas = dpss(len(x), NW=ancho, Kmax=cantidad, sym=True, norm=2)
espectros = []
for ventana in ventanas:
potencia = abs(np.fft.rfft(x*ventana))**2/(ventana@ventana)
espectros.append(unilateral(potencia, len(x)))
return np.fft.rfftfreq(len(x)), np.mean(espectros, axis=0), ventanas
fm, pm, ventanas = multitaper(x)
print("máxima falta de ortogonalidad DPSS:",
np.max(abs([email protected](len(ventanas)))))
print("estimaciones unilateral cruda, Welch y multitaper cerca de 1/8:",
p[256], pw[32], pm[256])The following comparison repeats independent white noise and examines frequency , which is interior and lies on the grid for each chosen size. True one-sided density is 2. Its variance does not disappear as grows; the Monte Carlo result fluctuates.
rng = np.random.default_rng(82)
reps = 2500
for n in (128, 512, 2048):
muestras = rng.normal(size=(reps,n))
ordenada = 2*abs(np.fft.rfft(muestras, axis=1)[:,n//8])**2/n
print("n, media y varianza de la ordenada:",
n, ordenada.mean(), ordenada.var(ddof=1))
print("media y varianza teóricas de la ordenada unilateral:", 2., 4.)Lab: long memory and a break
To simulate ARFIMA, approximate with a finite causal filter: and . A truncated tail and finite burn-in produce an approximation, especially delicate for near because weights decay slowly. Do not present it as an exact path from the infinite past.
def pesos_integracion(d, longitud):
pesos = np.empty(longitud)
pesos[0] = 1.
for j in range(1, longitud):
pesos[j] = pesos[j-1]*(j-1+d)/j
return pesos
def arfima_aproximado(d, n, truncacion, burn, rng):
if not 0 < d < .5 or min(n,truncacion,burn) <= 0:
raise ValueError("parámetros inválidos")
ruido = rng.normal(size=n+burn)
filtrada = signal.fftconvolve(ruido, pesos_integracion(d, truncacion), mode="full")[:len(ruido)]
return filtrada[burn:]
rng = np.random.default_rng(614)
serie = arfima_aproximado(.3, 2048, 1024, 1024, rng)
print("observaciones, media y varianza simuladas:",
len(serie), serie.mean(), serie.var())
print("primeros pesos de integración:", pesos_integracion(.3, 5))GPH uses only low positive frequencies. R/S and DFA group by non-overlapping scales in this example; their slopes are descriptive estimates, not confidence intervals. Compare the same realization before and after introducing a known artificial jump to observe how much a structural change affects each diagnostic.
def gph(x, m):
x = np.asarray(x, dtype=float)
n = len(x)
if not 2 <= m < n//2:
raise ValueError("número de frecuencias inválido")
j = np.arange(1,m+1)
omega = 2*np.pi*j/n
I = abs(np.fft.rfft(x-x.mean())[j])**2/n
if np.any(I <= 0):
raise ValueError("log-periodograma no definido")
z = np.log(4*np.sin(omega/2)**2)
return -np.polyfit(z, np.log(I), 1)[0]
def rs_dfa(x, escalas):
x = np.asarray(x, dtype=float)
perfil = np.cumsum(x-x.mean())
rs, fluctuacion = [], []
for s in escalas:
n_bloques = len(x)//s
if n_bloques < 2:
raise ValueError("cada escala necesita al menos dos bloques")
bloques = x[:n_bloques*s].reshape(n_bloques,s)
centrados = bloques-bloques.mean(axis=1, keepdims=True)
acumulados = np.cumsum(centrados,axis=1)
rango = acumulados.max(axis=1)-acumulados.min(axis=1)
sd = bloques.std(axis=1,ddof=1)
if np.any(sd <= 0):
raise ValueError("bloque de varianza nula")
rs.append(np.mean(rango/sd))
Y = perfil[:n_bloques*s].reshape(n_bloques,s)
t = np.arange(s)-(s-1)/2
nivel = Y.mean(axis=1,keepdims=True)
pendiente = ((Y-nivel)@t/(t@t))[:,None]
resid = Y-nivel-pendiente*t
fluctuacion.append(np.sqrt(np.mean(resid*resid)))
H_rs = np.polyfit(np.log(escalas), np.log(rs), 1)[0]
H_dfa = np.polyfit(np.log(escalas), np.log(fluctuacion), 1)[0]
return H_rs, H_dfa
escalas = np.array([16,32,64,128,256])
serie_salto = serie.copy()
inicio_salto = 7*len(serie)//13
serie_salto[inicio_salto:] += 8
print("índice del salto:", inicio_salto)
for nombre, datos in (("sin salto", serie), ("con salto", serie_salto)):
H_rs, H_dfa = rs_dfa(datos, escalas)
print(nombre, "d GPH, H R/S, H DFA:", gph(datos, 90), H_rs, H_dfa)Deviation from generating value combines sampling variation, filter truncation and frequency or scale choice. In this run, GPH moves from about 0.247 to 0.829 and the DFA slope from 0.790 to 1.233 after the jump. The latter slope does not prove that the process with a break is a stationary ARFIMA. The jump is added after simulation and known by construction; its position relative to blocks also matters, and in real data its date and size are usually unknown.
Exercises
Step 1 of 3. What is the response of the innovation filter?
Step 1 of 3. What variances do the real and imaginary DFT parts have?
import numpy as np
def fractional_difference(x, d, max_weights):
passThe spectral measure and autocovariance describe the same second-order dependence. Smoothing reduces variance at the cost of resolution; filters can create waves and apparent long memory can have different causes.