!pip install --upgrade quantecon import numpy as np import matplotlib.pyplot as plt %matplotlib inline from quantecon import ARMA, periodogram, ar_periodogram n = 40 # Data size ϕ, θ = 0.5, (0, -0.8) # AR and MA parameters lp = ARMA(ϕ, θ) X = lp.simulation(ts_length=n) fig, ax = plt.subplots() x, y = periodogram(X) ax.plot(x, y, 'b-', lw=2, alpha=0.5, label='periodogram') x_sd, y_sd = lp.spectral_density(two_pi=False, res=120) ax.plot(x_sd, y_sd, 'r-', lw=2, alpha=0.8, label='spectral density') ax.legend() plt.show() def hanning_window(M): w = [0.5 - 0.5 * np.cos(2 * np.pi * n/(M-1)) for n in range(M)] return w window = hanning_window(25) / np.abs(sum(hanning_window(25))) x = np.linspace(-12, 12, 25) fig, ax = plt.subplots(figsize=(9, 7)) ax.plot(x, window) ax.set_title("Hanning window") ax.set_ylabel("Weights") ax.set_xlabel("Position in sequence of weights") plt.show() ## Data n = 400 ϕ = 0.5 θ = 0, -0.8 lp = ARMA(ϕ, θ) X = lp.simulation(ts_length=n) fig, ax = plt.subplots(3, 1, figsize=(10, 12)) for i, wl in enumerate((15, 55, 175)): # Window lengths x, y = periodogram(X) ax[i].plot(x, y, 'b-', lw=2, alpha=0.5, label='periodogram') x_sd, y_sd = lp.spectral_density(two_pi=False, res=120) ax[i].plot(x_sd, y_sd, 'r-', lw=2, alpha=0.8, label='spectral density') x, y_smoothed = periodogram(X, window='hamming', window_len=wl) ax[i].plot(x, y_smoothed, 'k-', lw=2, label='smoothed periodogram') ax[i].legend() ax[i].set_title(f'window length = {wl}') plt.show() lp = ARMA(-0.9) wl = 65 fig, ax = plt.subplots(3, 1, figsize=(10,12)) for i in range(3): X = lp.simulation(ts_length=150) ax[i].set_xlim(0, np.pi) x_sd, y_sd = lp.spectral_density(two_pi=False, res=180) ax[i].semilogy(x_sd, y_sd, 'r-', lw=2, alpha=0.75, label='spectral density') x, y_smoothed = periodogram(X, window='hamming', window_len=wl) ax[i].semilogy(x, y_smoothed, 'k-', lw=2, alpha=0.75, label='standard smoothed periodogram') x, y_ar = ar_periodogram(X, window='hamming', window_len=wl) ax[i].semilogy(x, y_ar, 'b-', lw=2, alpha=0.75, label='AR smoothed periodogram') ax[i].legend(loc='upper left') plt.show()