{
"cells": [
{
"cell_type": "markdown",
"id": "78628fca",
"metadata": {},
"source": [
"\n",
""
]
},
{
"cell_type": "markdown",
"id": "8d611745",
"metadata": {},
"source": [
"# Estimation of Spectra\n",
"\n",
"\n",
""
]
},
{
"cell_type": "markdown",
"id": "6980d944",
"metadata": {},
"source": [
"## Contents\n",
"\n",
"- [Estimation of Spectra](#Estimation-of-Spectra) \n",
" - [Overview](#Overview) \n",
" - [Periodograms](#Periodograms) \n",
" - [Smoothing](#Smoothing) \n",
" - [Exercises](#Exercises) "
]
},
{
"cell_type": "markdown",
"id": "67da718f",
"metadata": {},
"source": [
"In addition to what’s in Anaconda, this lecture will need the following libraries:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d5ecaf90",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"!pip install --upgrade quantecon"
]
},
{
"cell_type": "markdown",
"id": "49062fad",
"metadata": {},
"source": [
"## Overview\n",
"\n",
"In a [previous lecture](https://python-advanced.quantecon.org/arma.html#arma), we covered some fundamental properties of covariance stationary linear stochastic processes.\n",
"\n",
"One objective for that lecture was to introduce spectral densities — a standard and very useful technique for analyzing such processes.\n",
"\n",
"In this lecture, we turn to the problem of estimating spectral densities and other related quantities from data.\n",
"\n",
"\n",
"\n",
"Estimates of the spectral density are computed using what is known as a periodogram — which in\n",
"turn is computed via the famous [fast Fourier transform](https://en.wikipedia.org/wiki/Fast_Fourier_transform).\n",
"\n",
"Once the basic technique has been explained, we will apply it to the analysis of several key macroeconomic time series.\n",
"\n",
"For supplementary reading, see [[Sargent, 1987](https://python-advanced.quantecon.org/zreferences.html#id197)] or [[Cryer and Chan, 2008](https://python-advanced.quantecon.org/zreferences.html#id143)].\n",
"\n",
"Let’s start with some standard imports:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "55206300",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"%matplotlib inline\n",
"from quantecon import ARMA, periodogram, ar_periodogram"
]
},
{
"cell_type": "markdown",
"id": "55056ce5",
"metadata": {},
"source": [
"\n",
""
]
},
{
"cell_type": "markdown",
"id": "ab860ff7",
"metadata": {},
"source": [
"## Periodograms\n",
"\n",
"[Recall that](https://python-advanced.quantecon.org/arma.html#arma-specd) the spectral density $ f $ of a covariance stationary process with\n",
"autocorrelation function $ \\gamma $ can be written\n",
"\n",
"$$\n",
"f(\\omega) = \\gamma(0) + 2 \\sum_{k \\geq 1} \\gamma(k) \\cos(\\omega k),\n",
"\\qquad \\omega \\in \\mathbb R\n",
"$$\n",
"\n",
"Now consider the problem of estimating the spectral density of a given time series, when $ \\gamma $ is unknown.\n",
"\n",
"In particular, let $ X_0, \\ldots, X_{n-1} $ be $ n $ consecutive observations of a single time series that is assumed to be covariance stationary.\n",
"\n",
"The most common estimator of the spectral density of this process is the *periodogram* of $ X_0, \\ldots, X_{n-1} $, which is defined as\n",
"\n",
"\n",
"\n",
"$$\n",
"I(\\omega)\n",
":= \\frac{1}{n} \\left| \\sum_{t=0}^{n-1} X_t e^{i t \\omega} \\right|^2,\n",
"\\qquad \\omega \\in \\mathbb R \\tag{29.1}\n",
"$$\n",
"\n",
"(Recall that $ |z| $ denotes the modulus of complex number $ z $)\n",
"\n",
"Alternatively, $ I(\\omega) $ can be expressed as\n",
"\n",
"$$\n",
"I(\\omega)\n",
"= \\frac{1}{n}\n",
"\\left\\{\n",
"\\left[\\sum_{t=0}^{n-1} X_t \\cos(\\omega t) \\right]^2 +\n",
"\\left[\\sum_{t=0}^{n-1} X_t \\sin(\\omega t) \\right]^2\n",
"\\right\\}\n",
"$$\n",
"\n",
"It is straightforward to show that the function $ I $ is even and $ 2\n",
"\\pi $-periodic (i.e., $ I(\\omega) = I(-\\omega) $ and $ I(\\omega +\n",
"2\\pi) = I(\\omega) $ for all $ \\omega \\in \\mathbb R $).\n",
"\n",
"From these two results, you will be able to verify that the values of\n",
"$ I $ on $ [0, \\pi] $ determine the values of $ I $ on all of\n",
"$ \\mathbb R $.\n",
"\n",
"The next section helps to explain the connection between the periodogram and the spectral density."
]
},
{
"cell_type": "markdown",
"id": "301b6b99",
"metadata": {},
"source": [
"### Interpretation\n",
"\n",
"\n",
"\n",
"To interpret the periodogram, it is convenient to focus on its values at the *Fourier frequencies*\n",
"\n",
"$$\n",
"\\omega_j := \\frac{2 \\pi j}{n},\n",
"\\quad j = 0, \\ldots, n - 1\n",
"$$\n",
"\n",
"In what sense is $ I(\\omega_j) $ an estimate of $ f(\\omega_j) $?\n",
"\n",
"The answer is straightforward, although it does involve some algebra.\n",
"\n",
"With a bit of effort, one can show that for any integer $ j > 0 $,\n",
"\n",
"$$\n",
"\\sum_{t=0}^{n-1} e^{i t \\omega_j }\n",
"= \\sum_{t=0}^{n-1} \\exp \\left\\{ i 2 \\pi j \\frac{t}{n} \\right\\} = 0\n",
"$$\n",
"\n",
"Letting $ \\bar X $ denote the sample mean $ n^{-1} \\sum_{t=0}^{n-1} X_t $, we then have\n",
"\n",
"$$\n",
"n I(\\omega_j)\n",
" = \\left| \\sum_{t=0}^{n-1} (X_t - \\bar X) e^{i t \\omega_j } \\right|^2\n",
" = \\sum_{t=0}^{n-1} (X_t - \\bar X) e^{i t \\omega_j }\n",
"\\sum_{r=0}^{n-1} (X_r - \\bar X) e^{-i r \\omega_j }\n",
"$$\n",
"\n",
"By carefully working through the sums, one can transform this to\n",
"\n",
"$$\n",
"n I(\\omega_j) = \\sum_{t=0}^{n-1} (X_t - \\bar X)^2 +\n",
"2 \\sum_{k=1}^{n-1} \\sum_{t=k}^{n-1} (X_t - \\bar X)(X_{t-k} - \\bar X)\n",
"\\cos(\\omega_j k)\n",
"$$\n",
"\n",
"Now let\n",
"\n",
"$$\n",
"\\hat \\gamma(k)\n",
":= \\frac{1}{n} \\sum_{t=k}^{n-1} (X_t - \\bar X)(X_{t-k} - \\bar X),\n",
"\\qquad k = 0,1,\\ldots, n-1\n",
"$$\n",
"\n",
"This is the sample autocovariance function, the natural “plug-in estimator” of the [autocovariance function](https://python-advanced.quantecon.org/arma.html#arma-defs) $ \\gamma $.\n",
"\n",
"(“Plug-in estimator” is an informal term for an estimator found by replacing expectations with sample means)\n",
"\n",
"With this notation, we can now write\n",
"\n",
"$$\n",
"I(\\omega_j) = \\hat \\gamma(0) +\n",
"2 \\sum_{k=1}^{n-1} \\hat \\gamma(k) \\cos(\\omega_j k)\n",
"$$\n",
"\n",
"Recalling our expression for $ f $ given [above](#periodograms),\n",
"we see that $ I(\\omega_j) $ is just a sample analog of $ f(\\omega_j) $."
]
},
{
"cell_type": "markdown",
"id": "00ddb8cb",
"metadata": {},
"source": [
"### Calculation\n",
"\n",
"\n",
"\n",
"Let’s now consider how to compute the periodogram as defined in [(29.1)](#equation-estspec-p).\n",
"\n",
"There are already functions available that will do this for us\n",
"— an example is `statsmodels.tsa.stattools.periodogram` in the `statsmodels` package.\n",
"\n",
"However, it is very simple to replicate their results, and this will give us a platform to make useful extensions.\n",
"\n",
"The most common way to calculate the periodogram is via the discrete Fourier transform,\n",
"which in turn is implemented through the [fast Fourier transform](https://en.wikipedia.org/wiki/Fast_Fourier_transform) algorithm.\n",
"\n",
"In general, given a sequence $ a_0, \\ldots, a_{n-1} $, the discrete\n",
"Fourier transform computes the sequence\n",
"\n",
"$$\n",
"A_j := \\sum_{t=0}^{n-1} a_t \\exp \\left\\{ i 2 \\pi \\frac{tj}{n} \\right\\},\n",
"\\qquad j = 0, \\ldots, n-1\n",
"$$\n",
"\n",
"With `numpy.fft.fft` imported as `fft` and $ a_0, \\ldots, a_{n-1} $ stored in NumPy array `a`, the function call `fft(a)` returns the values $ A_0, \\ldots, A_{n-1} $ as a NumPy array.\n",
"\n",
"It follows that when the data $ X_0, \\ldots, X_{n-1} $ are stored in array `X`, the values $ I(\\omega_j) $ at the Fourier frequencies, which are given by\n",
"\n",
"$$\n",
"\\frac{1}{n} \\left| \\sum_{t=0}^{n-1} X_t \\exp \\left\\{ i 2 \\pi \\frac{t j}{n} \\right\\} \\right|^2,\n",
"\\qquad j = 0, \\ldots, n-1\n",
"$$\n",
"\n",
"can be computed by `np.abs(fft(X))**2 / len(X)`.\n",
"\n",
">**Note**\n",
">\n",
">The NumPy function `abs` acts elementwise, and correctly handles complex numbers (by computing their modulus, which is exactly what we need).\n",
"\n",
"A function called `periodogram` that puts all this together can be found [here](https://github.com/QuantEcon/QuantEcon.py/blob/master/quantecon/estspec.py).\n",
"\n",
"Let’s generate some data for this function using the `ARMA` class from [QuantEcon.py](https://github.com/QuantEcon/QuantEcon.py) (see the [lecture on linear processes](https://python-advanced.quantecon.org/arma.html#arma) for more details).\n",
"\n",
"Here’s a code snippet that, once the preceding code has been run, generates data from the process\n",
"\n",
"\n",
"\n",
"$$\n",
"X_t = 0.5 X_{t-1} + \\epsilon_t - 0.8 \\epsilon_{t-2} \\tag{29.2}\n",
"$$\n",
"\n",
"where $ \\{ \\epsilon_t \\} $ is white noise with unit variance, and compares the periodogram to the actual spectral density"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6a715b3b",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"n = 40 # Data size\n",
"ϕ, θ = 0.5, (0, -0.8) # AR and MA parameters\n",
"lp = ARMA(ϕ, θ)\n",
"X = lp.simulation(ts_length=n)\n",
"\n",
"fig, ax = plt.subplots()\n",
"x, y = periodogram(X)\n",
"ax.plot(x, y, 'b-', lw=2, alpha=0.5, label='periodogram')\n",
"x_sd, y_sd = lp.spectral_density(two_pi=False, res=120)\n",
"ax.plot(x_sd, y_sd, 'r-', lw=2, alpha=0.8, label='spectral density')\n",
"ax.legend()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "58444a5f",
"metadata": {},
"source": [
"This estimate looks rather disappointing, but the data size is only 40, so\n",
"perhaps it’s not surprising that the estimate is poor.\n",
"\n",
"However, if we try again with `n = 1200` the outcome is not much better\n",
"\n",
"![https://python-advanced.quantecon.org/_static/lecture_specific/estspec/periodogram1.png](https://python-advanced.quantecon.org/_static/lecture_specific/estspec/periodogram1.png)\n",
"\n",
" \n",
"The periodogram is far too irregular relative to the underlying spectral density.\n",
"\n",
"This brings us to our next topic."
]
},
{
"cell_type": "markdown",
"id": "f925b825",
"metadata": {},
"source": [
"## Smoothing\n",
"\n",
"\n",
"\n",
"There are two related issues here.\n",
"\n",
"One is that, given the way the fast Fourier transform is implemented, the\n",
"number of points $ \\omega $ at which $ I(\\omega) $ is estimated\n",
"increases in line with the amount of data.\n",
"\n",
"In other words, although we have more data, we are also using it to estimate more values.\n",
"\n",
"A second issue is that densities of all types are fundamentally hard to\n",
"estimate without parametric assumptions.\n",
"\n",
"\n",
"\n",
"Typically, nonparametric estimation of densities requires some degree of smoothing.\n",
"\n",
"The standard way that smoothing is applied to periodograms is by taking local averages.\n",
"\n",
"In other words, the value $ I(\\omega_j) $ is replaced with a weighted\n",
"average of the adjacent values\n",
"\n",
"$$\n",
"I(\\omega_{j-p}), I(\\omega_{j-p+1}), \\ldots, I(\\omega_j), \\ldots, I(\\omega_{j+p})\n",
"$$\n",
"\n",
"This weighted average can be written as\n",
"\n",
"\n",
"\n",
"$$\n",
"I_S(\\omega_j) := \\sum_{\\ell = -p}^{p} w(\\ell) I(\\omega_{j+\\ell}) \\tag{29.3}\n",
"$$\n",
"\n",
"where the weights $ w(-p), \\ldots, w(p) $ are a sequence of $ 2p + 1 $ nonnegative\n",
"values summing to one.\n",
"\n",
"In general, larger values of $ p $ indicate more smoothing — more on\n",
"this below.\n",
"\n",
"The next figure shows the kind of sequence typically used.\n",
"\n",
"Note the smaller weights towards the edges and larger weights in the center, so that more distant values from $ I(\\omega_j) $ have less weight than closer ones in the sum [(29.3)](#equation-estspec-ws)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "890dad2c",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"def hanning_window(M):\n",
" w = [0.5 - 0.5 * np.cos(2 * np.pi * n/(M-1)) for n in range(M)]\n",
" return w\n",
"\n",
"window = hanning_window(25) / np.abs(sum(hanning_window(25)))\n",
"x = np.linspace(-12, 12, 25)\n",
"fig, ax = plt.subplots(figsize=(9, 7))\n",
"ax.plot(x, window)\n",
"ax.set_title(\"Hanning window\")\n",
"ax.set_ylabel(\"Weights\")\n",
"ax.set_xlabel(\"Position in sequence of weights\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "6b009f79",
"metadata": {},
"source": [
"### Estimation with Smoothing\n",
"\n",
"\n",
"\n",
"Our next step is to provide code that will not only estimate the periodogram but also provide smoothing as required.\n",
"\n",
"Such functions have been written in [estspec.py](https://github.com/QuantEcon/QuantEcon.py/blob/master/quantecon/estspec.py) and are available once you’ve installed [QuantEcon.py](http://quantecon.org/quantecon-py).\n",
"\n",
"The [GitHub listing](https://github.com/QuantEcon/QuantEcon.py/blob/master/quantecon/estspec.py) displays three functions, `smooth()`, `periodogram()`, `ar_periodogram()`. We will discuss the first two here and the third one [below](#ar-periodograms).\n",
"\n",
"The `periodogram()` function returns a periodogram, optionally smoothed via the `smooth()` function.\n",
"\n",
"Regarding the `smooth()` function, since smoothing adds a nontrivial amount of computation, we have applied a fairly terse array-centric method based around `np.convolve`.\n",
"\n",
"Readers are left either to explore or simply to use this code according to their interests.\n",
"\n",
"The next three figures each show smoothed and unsmoothed periodograms, as well as the population or “true” spectral density.\n",
"\n",
"(The model is the same as before — see equation [(29.2)](#equation-esp-arma) — and there are 400 observations)\n",
"\n",
"From the top figure to bottom, the window length is varied from small to large.\n",
"\n",
"\n",
"\n",
"![https://python-advanced.quantecon.org/_static/lecture_specific/estspec/window_smoothing.png](https://python-advanced.quantecon.org/_static/lecture_specific/estspec/window_smoothing.png)\n",
"\n",
" \n",
"In looking at the figure, we can see that for this model and data size, the\n",
"window length chosen in the middle figure provides the best fit.\n",
"\n",
"Relative to this value, the first window length provides insufficient\n",
"smoothing, while the third gives too much smoothing.\n",
"\n",
"Of course in real estimation problems, the true spectral density is not visible\n",
"and the choice of appropriate smoothing will have to be made based on\n",
"judgement/priors or some other theory.\n",
"\n",
"\n",
""
]
},
{
"cell_type": "markdown",
"id": "cc43fe94",
"metadata": {},
"source": [
"### Pre-Filtering and Smoothing\n",
"\n",
"\n",
"\n",
"In the [code listing](https://github.com/QuantEcon/QuantEcon.py/blob/master/quantecon/estspec.py), we showed three functions from the file `estspec.py`.\n",
"\n",
"The third function in the file (`ar_periodogram()`) adds a pre-processing step to periodogram smoothing.\n",
"\n",
"First, we describe the basic idea, and after that we give the code.\n",
"\n",
"The essential idea is to\n",
"\n",
"1. Transform the data in order to make estimation of the spectral density more efficient. \n",
"1. Compute the periodogram associated with the transformed data. \n",
"1. Reverse the effect of the transformation on the periodogram, so that it now\n",
" estimates the spectral density of the original process. \n",
"\n",
"\n",
"Step 1 is called *pre-filtering* or *pre-whitening*, while step 3 is called *recoloring*.\n",
"\n",
"The first step is called pre-whitening because the\n",
"transformation is usually designed to turn the data into something closer to white noise.\n",
"\n",
"Why would this be desirable in terms of spectral density estimation?\n",
"\n",
"The reason is that we are smoothing our estimated periodogram based on\n",
"estimated values at nearby points — recall [(29.3)](#equation-estspec-ws).\n",
"\n",
"The underlying assumption that makes this a good idea is that the true\n",
"spectral density is relatively regular — the value of $ I(\\omega) $ is close\n",
"to that of $ I(\\omega') $ when $ \\omega $ is close to $ \\omega' $.\n",
"\n",
"This will not be true in all cases, but it is certainly true for white noise.\n",
"\n",
"For white noise, $ I $ is as regular as possible — [it is a constant function](https://python-advanced.quantecon.org/arma.html#arma-wnsd).\n",
"\n",
"In this case, values of $ I(\\omega') $ at points $ \\omega' $ near to $ \\omega $\n",
"provided the maximum possible amount of information about the value $ I(\\omega) $.\n",
"\n",
"Another way to put this is that if $ I $ is relatively constant, then we can use a large amount of smoothing without introducing too much bias.\n",
"\n",
"\n",
""
]
},
{
"cell_type": "markdown",
"id": "1140e66c",
"metadata": {},
"source": [
"### The AR(1) Setting\n",
"\n",
"\n",
"\n",
"Let’s examine this idea more carefully in a particular setting — where\n",
"the data are assumed to be generated by an AR(1) process.\n",
"\n",
"(More general ARMA settings can be handled using similar techniques to those described below)\n",
"\n",
"Suppose in particular that $ \\{X_t\\} $ is covariance stationary and AR(1),\n",
"with\n",
"\n",
"\n",
"\n",
"$$\n",
"X_{t+1} = \\mu + \\phi X_t + \\epsilon_{t+1} \\tag{29.4}\n",
"$$\n",
"\n",
"where $ \\mu $ and $ \\phi \\in (-1, 1) $ are unknown parameters and $ \\{ \\epsilon_t \\} $ is white noise.\n",
"\n",
"It follows that if we regress $ X_{t+1} $ on $ X_t $ and an intercept, the residuals\n",
"will approximate white noise.\n",
"\n",
"Let\n",
"\n",
"- $ g $ be the spectral density of $ \\{ \\epsilon_t \\} $ — a constant function, as discussed above \n",
"- $ I_0 $ be the periodogram estimated from the residuals — an estimate of $ g $ \n",
"- $ f $ be the spectral density of $ \\{ X_t \\} $ — the object we are trying to estimate \n",
"\n",
"\n",
"In view of [an earlier result](https://python-advanced.quantecon.org/arma.html#arma-spec-den) we obtained while discussing ARMA processes, $ f $ and $ g $ are related by\n",
"\n",
"\n",
"\n",
"$$\n",
"f(\\omega) = \\left| \\frac{1}{1 - \\phi e^{i\\omega}} \\right|^2 g(\\omega) \\tag{29.5}\n",
"$$\n",
"\n",
"This suggests that the recoloring step, which constructs an estimate $ I $ of $ f $ from $ I_0 $, should set\n",
"\n",
"$$\n",
"I(\\omega) = \\left| \\frac{1}{1 - \\hat \\phi e^{i\\omega}} \\right|^2 I_0(\\omega)\n",
"$$\n",
"\n",
"where $ \\hat \\phi $ is the OLS estimate of $ \\phi $.\n",
"\n",
"The code for `ar_periodogram()` — the third function in `estspec.py` — does exactly this. (See the code [here](https://github.com/QuantEcon/QuantEcon.py/blob/master/quantecon/estspec.py)).\n",
"\n",
"The next figure shows realizations of the two kinds of smoothed periodograms\n",
"\n",
"1. “standard smoothed periodogram”, the ordinary smoothed periodogram, and \n",
"1. “AR smoothed periodogram”, the pre-whitened and recolored one generated by `ar_periodogram()` \n",
"\n",
"\n",
"The periodograms are calculated from time series drawn from [(29.4)](#equation-estspec-ar-dgp) with $ \\mu = 0 $ and $ \\phi = -0.9 $.\n",
"\n",
"Each time series is of length 150.\n",
"\n",
"The difference between the three subfigures is just randomness — each one uses a different draw of the time series.\n",
"\n",
"\n",
"\n",
"![https://python-advanced.quantecon.org/_static/lecture_specific/estspec/ar_smoothed_periodogram.png](https://python-advanced.quantecon.org/_static/lecture_specific/estspec/ar_smoothed_periodogram.png)\n",
"\n",
" \n",
"In all cases, periodograms are fit with the “hamming” window and window length of 65.\n",
"\n",
"Overall, the fit of the AR smoothed periodogram is much better, in the sense\n",
"of being closer to the true spectral density."
]
},
{
"cell_type": "markdown",
"id": "c03e7166",
"metadata": {},
"source": [
"## Exercises\n",
"\n",
"\n",
""
]
},
{
"cell_type": "markdown",
"id": "06dc8238",
"metadata": {},
"source": [
"## Exercise 29.1\n",
"\n",
"Replicate [this figure](#fig-window-smoothing) (modulo randomness).\n",
"\n",
"The model is as in equation [(29.2)](#equation-esp-arma) and there are 400 observations.\n",
"\n",
"For the smoothed periodogram, the window type is “hamming”."
]
},
{
"cell_type": "markdown",
"id": "53d129d7",
"metadata": {},
"source": [
"## Solution to[ Exercise 29.1](https://python-advanced.quantecon.org/#est_ex1)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ea7fae52",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"## Data\n",
"n = 400\n",
"ϕ = 0.5\n",
"θ = 0, -0.8\n",
"lp = ARMA(ϕ, θ)\n",
"X = lp.simulation(ts_length=n)\n",
"\n",
"fig, ax = plt.subplots(3, 1, figsize=(10, 12))\n",
"\n",
"for i, wl in enumerate((15, 55, 175)): # Window lengths\n",
"\n",
" x, y = periodogram(X)\n",
" ax[i].plot(x, y, 'b-', lw=2, alpha=0.5, label='periodogram')\n",
"\n",
" x_sd, y_sd = lp.spectral_density(two_pi=False, res=120)\n",
" ax[i].plot(x_sd, y_sd, 'r-', lw=2, alpha=0.8, label='spectral density')\n",
"\n",
" x, y_smoothed = periodogram(X, window='hamming', window_len=wl)\n",
" ax[i].plot(x, y_smoothed, 'k-', lw=2, label='smoothed periodogram')\n",
"\n",
" ax[i].legend()\n",
" ax[i].set_title(f'window length = {wl}')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "1d6a17c5",
"metadata": {},
"source": [
"\n",
""
]
},
{
"cell_type": "markdown",
"id": "e9f1df57",
"metadata": {},
"source": [
"## Exercise 29.2\n",
"\n",
"Replicate [this figure](#fig-ar-smoothed-periodogram) (modulo randomness).\n",
"\n",
"The model is as in equation [(29.4)](#equation-estspec-ar-dgp), with $ \\mu = 0 $, $ \\phi = -0.9 $\n",
"and 150 observations in each time series.\n",
"\n",
"All periodograms are fit with the “hamming” window and window length of 65."
]
},
{
"cell_type": "markdown",
"id": "4afd664f",
"metadata": {},
"source": [
"## Solution to[ Exercise 29.2](https://python-advanced.quantecon.org/#est_ex2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ea44b533",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"lp = ARMA(-0.9)\n",
"wl = 65\n",
"\n",
"\n",
"fig, ax = plt.subplots(3, 1, figsize=(10,12))\n",
"\n",
"for i in range(3):\n",
" X = lp.simulation(ts_length=150)\n",
" ax[i].set_xlim(0, np.pi)\n",
"\n",
" x_sd, y_sd = lp.spectral_density(two_pi=False, res=180)\n",
" ax[i].semilogy(x_sd, y_sd, 'r-', lw=2, alpha=0.75,\n",
" label='spectral density')\n",
"\n",
" x, y_smoothed = periodogram(X, window='hamming', window_len=wl)\n",
" ax[i].semilogy(x, y_smoothed, 'k-', lw=2, alpha=0.75,\n",
" label='standard smoothed periodogram')\n",
"\n",
" x, y_ar = ar_periodogram(X, window='hamming', window_len=wl)\n",
" ax[i].semilogy(x, y_ar, 'b-', lw=2, alpha=0.75,\n",
" label='AR smoothed periodogram')\n",
"\n",
" ax[i].legend(loc='upper left')\n",
"plt.show()"
]
}
],
"metadata": {
"date": 1714698770.7164557,
"filename": "estspec.md",
"kernelspec": {
"display_name": "Python",
"language": "python3",
"name": "python3"
},
"title": "Estimation of Spectra"
},
"nbformat": 4,
"nbformat_minor": 5
}