Module contents
Lesson 14 of 31Advanced 110 min

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

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.

InteractivePoles, zeros and spectrum

Each upper point has a lower conjugate. In the z plane, poles and zeroes are inverses of roots of polynomials in lag operator B. For p=reⁱᶿ and q=seⁱᵞ, use φ(B)=(1−pB)(1−p̄B) and θ(B)=(1−qB)(1−q̄B), with unit-variance innovations.

Pole-zero plane

Real part horizontal; imaginary part vertical

Theoretical spectral density

Angular frequency ω, radians per sample
  • Conjugate poles
  • Conjugate zeroes
  • Theoretical density

Path simulated with these same roots

Path time

For the stable causal representation, f(ω)=|θ(e⁻ⁱω)/φ(e⁻ⁱω)|²/(2π), with ω between −π and π. Only 0≤ω≤π is shown because density is even; integrating both halves gives variance. The chart grid has 513 frequencies and the indicated maximum is discrete. Frequency ν in cycles per sample equals ω/(2π), with period 1/ν if ν>0.

A pole near the circle may accentuate frequencies near its angle and a zero may attenuate them; the maximum depends on all factors and need not equal the pole angle. The causal filter is stable if pole modulus is below one; the MA representation is invertible if zero modulus is below one. Common factors may cancel; the shown representation is classified before cancellation.

The simulation uses seeded normal innovations, zero start and, for stable poles, discards 600 steps. Near the boundary this burn-in may not remove the transient. Outside the stable region only the zero-start path is shown and no stationary causal density is attributed to that representation.

0.92
0.80
0.55
2.10
AR representationStable causal
MA representationInvertible
Grid maximum: ω0.792 rad
Grid maximum: cycles/sample0.1260
Seed2614
Adjust the filter and compare its theoretical spectral density with a simulated path. Roots and the frequency convention are shown in the figure.

Variance distributed over frequency

For a real centered weakly stationary process, a spectral density ff is normalized here per radian:

γ(h)=∫−ππeihωf(ω) dω,f(ω)=12π∑h=−∞∞γ(h)e−ihω,\gamma(h)=\int_{-\pi}^{\pi} e^{ih\omega}f(\omega)\,d\omega, \qquad f(\omega)=\frac1{2\pi}\sum_{h=-\infty}^{\infty}\gamma(h)e^{-ih\omega},

when the autocovariance series is absolutely summable. Thus γ(0)=∫−ππf(ω) dω\gamma(0)=\int_{-\pi}^{\pi}f(\omega)\,d\omega. For white noise with variance σ2\sigma^2, f(ω)=σ2/(2π)f(\omega)=\sigma^2/(2\pi). Angular frequency ω\omega is in radians per sample; ν=ω/(2π)\nu=\omega/(2\pi) is in cycles per sample and a nonzero cycle has period 1/ν1/\nu samples. Changing units also changes density: per cycle, g(ν)=2πf(2πν)g(\nu)=2\pi f(2\pi\nu).

The Herglotz spectral representation is more general: a nonnegative-definite autocovariance function corresponds to a finite nonnegative measure FF on the circle, with

γ(h)=∫−ππeihω dF(ω).\gamma(h)=\int_{-\pi}^{\pi}e^{ih\omega}\,dF(\omega).

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 L2L^2 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

Xt=Vt+∑j=0∞ψjεt−j,ψ0=1,∑jψj2<∞.X_t=V_t+\sum_{j=0}^{\infty}\psi_j\varepsilon_{t-j}, \qquad \psi_0=1,\qquad \sum_j\psi_j^2<\infty.

Innovations are uncorrelated, VtV_t is orthogonal to them and represents the linearly deterministic part from the infinite past. If the process is purely nondeterministic, Vt=0V_t=0. 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 Yt=∑jajXt−jY_t=\sum_j a_jX_{t-j} with absolutely summable coefficients has response A(e−iω)=∑jaje−ijωA(e^{-i\omega})=\sum_j a_je^{-ij\omega} and density

fY(ω)=∣A(e−iω)∣2fX(ω).f_Y(\omega)=|A(e^{-i\omega})|^2f_X(\omega).

For a causal ARMA with innovation variance σ2\sigma^2 and polynomials from the previous lesson,

fX(ω)=σ22π∣θ(e−iω)∣2∣ϕ(e−iω)∣2.f_X(\omega)=\frac{\sigma^2}{2\pi} \frac{|\theta(e^{-i\omega})|^2}{|\phi(e^{-i\omega})|^2}.

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 re±iαre^{\pm i\alpha} and white noise, if the maximum is interior,

cos⁡ωmax⁡=1+r22rcos⁡α.\cos\omega_{\max}=\frac{1+r^2}{2r}\cos\alpha.

If the right-hand side lies outside [−1,1][-1,1], the maximum is at an endpoint of [0,π][0,\pi]. This distinction matters even when rr is close to one.

The Slutsky effect shows that filtering noise can create apparently regular oscillations. Composing sums and differences changes ∣A∣2|A|^2: 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.

InteractiveWaves created by a filter

First 120 values

Time in samples

Exact spectral gain

Frequency in cycles per sample
  • Original noise / gain 1
  • Output / filter gain

Noise is independent normal with variance one. The finite filter is A(B)=c·[(1+B)/2]ˢ(1−B)ᵈ, with c chosen so coefficient squares sum to one. Output therefore also has theoretical variance one: the chart shows how that variance is redistributed across frequency. The curve is |A(e⁻ⁱω)|² with ω=2πf; it is not an estimate from the path.

The indicated frequency is the maximum on a 251-point grid; it may be at an endpoint. The same sequence is filtered for each adjustment and prior history is included to avoid initial zeroes. Waves result from filtering noise; they do not prove an external oscillator exists.

5
1
Filter coefficients7
Grid-maximum frequency0.134 cycles/sample
Maximum gain3.266
Theoretical output variance1
Seed2614
Apply sums and differences to the same white noise. The gain curve is the exact response of the normalized filter.

Why the raw periodogram does not stabilize

The periodogram of x0,…,xn−1x_0,\ldots,x_{n-1}, under the preceding convention, is

In(ω)=1n∣∑t=0n−1xte−iωt∣2.I_n(\omega)=\frac1n\left|\sum_{t=0}^{n-1}x_te^{-i\omega t}\right|^2.

For iid Gaussian noise with variance σ2\sigma^2, at interior Fourier frequencies 2πk/n2\pi k/n other than zero or Nyquist, In/σ2I_n/\sigma^2 is exponential with mean one. At those frequencies its variance is σ4\sigma^4 for every nn: 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 n−∣h∣n-|h| pairs with lag hh:

EIn(ω)=∑∣h∣<n(1−∣h∣n)γ(h)e−ihω.\mathbb E I_n(\omega)=\sum_{|h|<n}\left(1-\frac{|h|}{n}\right)\gamma(h)e^{-ih\omega}.

If ∑h∣γ(h)∣<∞\sum_h|\gamma(h)|<\infty, dominated convergence gives 2πf(ω)2\pi f(\omega). 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 f(ω)>0f(\omega)>0, the DFT central limit theorem gives two asymptotically independent Gaussian components and Var⁡In→[2πf(ω)]2\operatorname{Var} I_n\to[2\pi f(\omega)]^2. Ratio In/[2πf(ω)]I_n/[2\pi f(\omega)] 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.

InteractiveMore data, a still-noisy periodogram

One realization: spectral estimates at frequencies common to segments

Frequency in cycles per observation; vertical line at 1/8
  • Periodograma
  • Welch
  • Sine multitaper
  • True spectrum

At f = 1/8: bars from 10th to 90th percentile and dots at mean of 120 replicates

Density estimate; dashed line = true value

All series have marginal variance 1. AR(1) is Xₜ = 0.8Xₜ₋₁ + 0.6εₜ, with stationary start and independent normal εₜ. We use two-sided density S(f), in cycles per observation, whose integral from −1/2 to 1/2 is variance: S = 1 for white noise. Positive frequencies are not doubled and the known mean, zero, is not subtracted.

Welch averages 4 disjoint segments of length 64, with periodic Hann and normalization by the window sum of squares. Multitaper averages 4 orthonormal sine windows hₖ(t) = √(2/(n+1)) sin(πk(t+1)/(n+1)), t = 0,…,n−1. They are sinusoidal tapers, not Thomson DPSS. Both alternatives widen the spectral window and may bias peaks or valleys: use AR(1) to see it.

For Gaussian white noise and this interior Fourier frequency, the raw ordinate has exponential distribution with mean and deviation 1 for each n: increasing n does not make it consistent. Welch with a fixed number of segments does not eliminate its variation either; under regular conditions both segment count and length must grow. For sine multitaper, consistent smoothing also requires more tapers and relative bandwidth K/n tending to zero. The 120 replicates are finite and their summaries fluctuate with the seed.

Process
256
4
4
True spectrum at f = 1/81.000
Periodogram: mean · deviation1.017 · 1.047
Welch: mean · deviation1.054 · 0.491
Sines: mean · deviation0.999 · 0.489
Replicates and seed120 · 2614
Compare realizations and estimator distributions for different sizes and smoothers. Replications use the displayed model and the spectral scale is indicated.

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 nn 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 W→0W\to0 and nW→∞nW\to\infty. 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(0,d,0)(0,d,0) for 0<d<1/20<d<1/2:

(1−B)dXt=εt,fX(ω)=σε22π∣1−e−iω∣−2d.(1-B)^dX_t=\varepsilon_t,\qquad f_X(\omega)=\frac{\sigma_\varepsilon^2}{2\pi} |1-e^{-i\omega}|^{-2d}.

The fractional operator is defined by its binomial series and requires convergence control. Near zero fX(ω)f_X(\omega) grows as ∣ω∣−2d|\omega|^{-2d} but remains integrable for d<1/2d<1/2. ACF decays as a power with exponent 2d−12d-1 and is not absolutely summable. By contrast, for a causal AR(1) with fixed coefficient, ACF decays geometrically. In ARFIMA with 0<d<1/20<d<1/2, mean variance asymptotically decays as a constant times n2d−1n^{2d-1}, slower than 1/n1/n.

InteractiveShort and long memory with equal variance

Theoretical ACF on log-log scale for positive lags.

  • AR(1)
  • ARFIMA(0,d,0)

Spectral density per radian near the origin, for positive angular frequency ω.

  • AR(1)
  • ARFIMA(0,d,0)

Exact sample-mean variance versus n; the vertical line marks selected n.

  • AR(1)
  • ARFIMA(0,d,0)

Both processes have zero mean and variance 1. AR(1) uses 0 < φ < 1 and innovation variance 1−φ². ARFIMA satisfies (1−B)ᵈXₜ = εₜ with 0 < d < 1/2 and innovation variance Γ(1−d)²/Γ(1−2d). φ is limited to positive values to show its ACF logarithmically.

AR ACF is φᵏ. ARFIMA starts at ρ(0)=1 and applies ρ(k)=ρ(k−1)(k−1+d)/(k−d). The AR curve stops when below 10⁻⁶, the plot’s lower limit. At large lags the first decays exponentially and the second as k^(2d−1).

Fractional density is σ²ε |2 sin(ω/2)|^(−2d)/(2π); it diverges near zero but its integral is finite because d < 1/2. It is drawn from ω=10⁻⁴, not zero. Each mean’s variance is calculated exactly as [n + 2Σₖ₌₁ⁿ⁻¹(n−k)ρ(k)]/n²: for large n it decays as 1/n in AR(1) and n^(2d−1) in ARFIMA. A finite sample can differ in appearance from its asymptotic regime.

0.30
0.85
200
Variance of each process1
AR(1) mean variance, n = 2000.05978
ARFIMA mean variance, n = 2000.10858
ARFIMA asymptotic exponent−0.40
ARFIMA innovation variance0.7596
Compare autocorrelations, spectra and finite mean variance; the spectral origin is not evaluated because fractional density diverges there.

The GPH estimator regresses the low-frequency log-periodogram on log⁡[4sin⁡2(ω/2)]\log[4\sin^2(\omega/2)]; its slope estimates −d-d. 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 H=d+1/2H=d+1/2, but finite estimates can differ greatly and an estimate of HH 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.

[ ]Periodogram and Welch from scratchBrowser
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 1/n1/n. 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.

[ ]Multitaper with DPSSBrowser
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 1/81/8, which is interior and lies on the grid for each chosen size. True one-sided density is 2. Its variance does not disappear as nn grows; the Monte Carlo result fluctuates.

[ ]Variance of a raw ordinateBrowser
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(0,d,0)(0,d,0), approximate (1−B)−d(1-B)^{-d} with a finite causal filter: ψ0=1\psi_0=1 and ψj=ψj−1(j−1+d)/j\psi_j=\psi_{j-1}(j-1+d)/j. A truncated tail and finite burn-in produce an approximation, especially delicate for dd near 1/21/2 because weights decay slowly. Do not present it as an exact path from the infinite past.

[ ]ARFIMA approximated by a fractional filterBrowser
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.

[ ]GPH, R/S y DFABrowser
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 d=0.3d=0.3 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

ProofFrom filter to variance
Prove: For Xₜ=φXₜ₋₁+εₜ, |φ|<1 and Var(εₜ)=σ², derive f(ω) and verify that its integral is the process variance.
0
Use the causal-filter response and geometric expansion.

Step 1 of 3. What is the response of the innovation filter?

ProofCorrect expectation, persistent variance
Prove: For iid Gaussian noise with variance σ² and an interior Fourier frequency, prove E[Iₙ]=σ² and Var(Iₙ)=σ⁴ with Iₙ=|DFT|²/n.
0
Separate the real and imaginary parts of the transform.

Step 1 of 3. What variances do the real and imaginary DFT parts have?

NumericPole angle and spectral peak
An AR(2) has inverse roots 0.95 exp(±iπ/6) and white noise. Calculate the interior spectral-maximum frequency in cycles per sample.
CodeDifference and reconstruct
Implement fractional_difference(x, d, max_weights): causally apply the first max_weights coefficients of (1−B)^d, with w₀=1 and wⱼ=wⱼ₋₁(j−1−d)/j. Return a series of the same length assuming zeros before the start, and reject max_weights below one. Check inversion with −d; if weights are truncated before the series length, recovery is only approximate.
import numpy as np

def fractional_difference(x, d, max_weights):
  pass
Shift+Enter to run
QuizA narrow peak next to a powerful band
You have a short series and want to distinguish a narrow peak from a nearby high-power band. Which decision is most defensible?
Key idea

The 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.