Coverage for HARK/Calibration/cpi/us/CPITools.py: 86%
28 statements
« prev ^ index » next coverage.py v7.11.0, created at 2025-11-02 05:14 +0000
« prev ^ index » next coverage.py v7.11.0, created at 2025-11-02 05:14 +0000
1"""
2Created on Wed Jan 20 18:07:41 2021
4@author: Mateo
5"""
7import os
8import urllib.request
10import numpy as np
11import pandas as pd
13from HARK import _log
15__all__ = ["get_cpi_series", "cpi_deflator"]
17us_cpi_dir = os.path.dirname(os.path.abspath(__file__))
20def download_cpi_series():
21 """
22 A method that downloads the cpi research series file directly from the
23 bls site onto the working directory.
24 After being converted to a .csv, this is the file that the rest of
25 the functions in this script use and must be placed in HARK/Calibration/cpi/us.
26 This function is not for users but for whenever mantainers want to update
27 the cpi series as new data comes out.
29 Returns
30 -------
31 None.
33 """
34 urllib.request.urlretrieve(
35 "https://www.bls.gov/cpi/research-series/r-cpi-u-rs-allitems.xlsx",
36 "r-cpi-u-rs-allitems.xlsx",
37 )
40def get_cpi_series():
41 """
42 This function reads the cpi series currently in the toolbox and returns it
43 as a pandas dataframe.
45 Returns
46 -------
47 cpi : Pandas DataFrame
48 DataFrame representation of the CPI research series file from the
49 Bureau of Labor Statistics.
51 """
53 cpi = pd.read_csv(
54 os.path.join(us_cpi_dir, "r-cpi-u-rs-allitems.csv"),
55 skiprows=5,
56 index_col=0,
57 )
58 return cpi
61def cpi_deflator(from_year, to_year, base_month=None):
62 """
63 Finds cpi deflator to transform quantities measured in "from_year" U.S.
64 dollars to "to_year" U.S. dollars.
65 The deflators are computed using the "r-cpi-u-rs" series from the BLS.
67 Parameters
68 ----------
69 from_year : int
70 Base year in which the nominal quantities are currently expressed.
71 to_year : int
72 Target year in which you wish to express the quantities.
73 base_month : str, optional
74 Month at which to take the CPI measurements to calculate the deflator.
75 The default is None, and in this case annual averages of the CPI are
76 used.
78 Returns
79 -------
80 deflator : numpy array
81 A length-1 numpy array with the deflator that, when multiplied by the
82 original nominal quantities, rebases them to "to_year" U.S. dollars.
84 """
86 # Check years are conforming
87 assert type(from_year) is int and type(to_year) is int, "Years must be integers."
89 # Check month is conforming
90 if base_month is not None:
91 months = [
92 "JAN",
93 "FEB",
94 "MAR",
95 "APR",
96 "MAY",
97 "JUNE",
98 "JULY",
99 "AUG",
100 "SEP",
101 "OCT",
102 "NOV",
103 "DEC",
104 ]
106 assert base_month in months, (
107 "If a month is provided, it must be " + "one of " + ",".join(months) + "."
108 )
110 column = base_month
112 else:
113 _log.debug("No base month was provided. Using annual CPI averages.")
114 column = "AVG"
116 # Get cpi and subset the columns we need.
117 cpi = get_cpi_series()
118 cpi_series = cpi[[column]].dropna()
120 try:
121 deflator = np.divide(
122 cpi_series.loc[to_year].to_numpy(), cpi_series.loc[from_year].to_numpy()
123 )
125 except KeyError as e:
126 message = (
127 "Could not find a CPI value for the requested " + "year-month combinations."
128 )
129 raise Exception(message).with_traceback(e.__traceback__)
131 return deflator