Skip to content

Instantly share code, notes, and snippets.

@harryposner
Last active August 27, 2021 01:54
Show Gist options
  • Save harryposner/ab51fd496e9e48ac39847cada10f6557 to your computer and use it in GitHub Desktop.
Save harryposner/ab51fd496e9e48ac39847cada10f6557 to your computer and use it in GitHub Desktop.
Add NBER recession bars to Matplotlib axes for time series plots
"""MIT License
Copyright (c) 2019-2021 Harry Posner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import pandas as pd
# See https://www.nber.org/cycles for the most up-to-date business cycle dates
DATES = (pd.DataFrame([
# PEAK , TROUGH
("" , "1854-12"),
("1857-06", "1858-12"),
("1860-10", "1861-06"),
("1865-04", "1867-12"),
("1869-06", "1870-12"),
("1873-10", "1879-03"),
("1882-03", "1885-05"),
("1887-03", "1888-04"),
("1890-07", "1891-05"),
("1893-01", "1894-06"),
("1895-12", "1897-06"),
("1899-06", "1900-12"),
("1902-09", "1904-08"),
("1907-05", "1908-06"),
("1910-01", "1912-01"),
("1913-01", "1914-12"),
("1918-08", "1919-03"),
("1920-01", "1921-07"),
("1923-05", "1924-07"),
("1926-10", "1927-11"),
("1929-08", "1933-03"),
("1937-05", "1938-06"),
("1945-02", "1945-10"),
("1948-11", "1949-10"),
("1953-07", "1954-05"),
("1957-08", "1958-04"),
("1960-04", "1961-02"),
("1969-12", "1970-11"),
("1973-11", "1975-03"),
("1980-01", "1980-07"),
("1981-07", "1982-11"),
("1990-07", "1991-03"),
("2001-03", "2001-11"),
("2007-12", "2009-06"),
("2020-02", "2020-04"),
])
.apply(pd.to_datetime)
.rename(columns={0: "Peak month", 1: "Trough month"})
)
def add_recession_bars(ax,
date_bounds=None,
method="trough",
caption=False):
"""Add recession bars to a Matplotlib axes with datetime x-axis
Parameters
----------
ax : Matplotlib axes
The axes to which to add recession bars
date_bounds : {iterable, None}, default None
Iterable of length 2, indicating start and end dates for recession bars.
Can use any format parseable by pd.to_datetime. If None, works from
existing bounds of x-axis.
method : {"trough", "midpoint", "peak"}, default "trough"
Method for choosing exact start and end of recessionary period.
Equivalent to FRED series USREC, USRECM, and USRECP respectively.
caption : boolean, default False
Add caption to axes' parent figure reading "Shaded areas indicate U.S.
recessions"
Returns
-------
ax : The original axes passed to the function
"""
dates = DATES + {"trough": pd.DateOffset(months=1),
"midpoint": pd.DateOffset(days=14),
"peak": pd.DateOffset(0)}[method]
if pd.isnull(dates["Trough month"].iloc[-1]):
# If we're currently in a recession, shade right up to now
dates["Trough month"].iloc[-1] = pd.to_datetime("today").floor("D")
if date_bounds is not None:
d_start, d_end = map(pd.to_datetime, date_bounds)
else:
d_start, d_end = (pd.Timestamp.fromordinal(int(x)) for x in ax.get_xlim())
dates = dates[(dates["Trough month"] > d_start) &
(dates["Peak month"] < d_end)]
if dates["Peak month"].iloc[0] < d_start:
dates["Peak month"].iloc[0] = d_start
if dates["Trough month"].iloc[-1] > d_end:
dates["Trough month"].iloc[-1] = d_end
y1, y2 = ax.get_ylim()
for row in dates.iterrows():
x = row[1]
ax.fill_between(x.values, y1=y1, y2=y2, color="lightgrey")
if caption:
(ax
.get_figure()
.text(0.01, 0.01, "Shaded areas indicate U.S. recessions")
)
return ax
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment