Last active
September 13, 2022 18:31
-
-
Save mchapman87501/0eeada9e78e56b719b368fa5d62546cc to your computer and use it in GitHub Desktop.
Plot month-to-month inflation using data from https://download.bls.gov/pub/time.series/cu/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import pandas as pd | |
import matplotlib.pyplot as plt | |
import matplotlib.ticker as ticker | |
data = pd.read_csv("data/cu.data.1.AllItems.txt", sep=r"[ \t]+", engine="python") | |
# Get 'All items in U.S. city average, all urban consumers, seasonally adjusted' | |
overall = data[data["series_id"] == "CUSR0000SA0"] | |
# NB: pct_change() computes fractional change. | |
monthly_pct = overall["value"].pct_change() * 100.0 | |
period_str = overall["period"].str.removeprefix("M") | |
year_str = overall["year"].astype(str) | |
dates = pd.to_datetime(year_str + "-" + period_str + "-01") | |
num_periods = 36 | |
value_label = "Inflation %" | |
date_label = "Month" | |
monthly_df = pd.DataFrame({date_label: dates, value_label: monthly_pct}).tail(num_periods) | |
# https://stackoverflow.com/a/30135182 | |
tick_labels = [""] * len(monthly_df[date_label]) | |
tick_labels[-1:0:-4] = [curr_date.strftime("%b\n%Y") for curr_date in monthly_df[date_label][-1:0:-4]] | |
ax = monthly_df.plot(x=date_label, y=value_label, kind="bar") | |
ax.xaxis.set_major_formatter(ticker.FixedFormatter(tick_labels)) | |
ax.annotate("Source: https://download.bls.gov/pub/time.series/cu/", xy=(0, -0.25), xycoords="axes fraction") | |
ax.set(xlabel=None) | |
plt.gcf().autofmt_xdate() | |
plt.savefig("cost_vs_time.png") | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment