#!/usr/bin/env python # encoding: utf-8 """ Consumer Price Index conversions 2010-02-21 by Ryan Greenberg Convert nominal dollars to real dollars using consumer price index from the Bureau of Labor Statistics. ftp://ftp.bls.gov/pub/special.requests/cpi/cpiai.txt Example: Convert $1 in 1974 to 2006 dollars import cpi cpi_convert = cpi.CPI(open('cpi_rates.txt', 'r')) # path to cpi data file print cpi_convert.real_dollars(1, 1974, 2006) ==> 4.0892494929 The input text file, cpi_rates.txt, is a tab-separated list of years and the average CPI for that year. """ import sys import os import re class CPI(): """Loads the specified year/average CPI table which can be used for conversions from nominal dollars to real dollars.""" def __init__(self, file): self.rates = {} for year in file: year = year.split("\t") if re.match('\d{4}', year[0]): self.rates[int(year[0])] = float(year[1]) else: pass def real_dollars(self, dollars, frm, to): """Returns dollars in to year using from year. from dollars = to dollars * to CPI / from CPI See http://www.polsci.wvu.edu/duval/ps300/Notes/ConvertNom_to_Real_dollars.htm""" try: frm = int(frm) to = int(to) except Exception, e: raise Exception("Conversion year must be a number") if isinstance(dollars, str): dollars = float(dollars.replace('$', '').replace(',', '')) if frm in self.rates and to in self.rates: return dollars * self.rates[to] / self.rates[frm] elif frm not in self.rates: raise Exception("Cannot convert to real dollars: %s not in CPI lookup table" % str(frm)) else: raise Exception("Cannot convert to real dollars: %s not in CPI lookup table" % str(to)) def main(): print __doc__ if __name__ == '__main__': main()