RealDollarsClass

From CS 294-10 Visualization Sp10

Jump to: navigation, search

Python Class

#!/usr/bin/env python
# encoding: utf-8
"""
cpi.py
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

2010-02-21 by Ryan Greenberg
"""

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():
	cpi_convert = CPI(open('cpi.txt', 'r'))
	print cpi_convert.real_dollars(1, 1974, 2006)
	
if __name__ == '__main__':
	main()

CPI Data

Year	Annual	CPI
1913	9.9
1914	10.0
1915	10.1
1916	10.9
1917	12.8
1918	15.1
1919	17.3
1920	20.0
1921	17.9
1922	16.8
1923	17.1
1924	17.1
1925	17.5
1926	17.7
1927	17.4
1928	17.1
1929	17.1
1930	16.7
1931	15.2
1932	13.7
1933	13.0
1934	13.4
1935	13.7
1936	13.9
1937	14.4
1938	14.1
1939	13.9
1940	14.0
1941	14.7
1942	16.3
1943	17.3
1944	17.6
1945	18.0
1946	19.5
1947	22.3
1948	24.1
1949	23.8
1950	24.1
1951	26.0
1952	26.5
1953	26.7
1954	26.9
1955	26.8
1956	27.2
1957	28.1
1958	28.9
1959	29.1
1960	29.6
1961	29.9
1962	30.2
1963	30.6
1964	31.0
1965	31.5
1966	32.4
1967	33.4
1968	34.8
1969	36.7
1970	38.8
1971	40.5
1972	41.8
1973	44.4
1974	49.3
1975	53.8
1976	56.9
1977	60.6
1978	65.2
1979	72.6
1980	82.4
1981	90.9
1982	96.5
1983	99.6
1984	103.9
1985	107.6
1986	109.6
1987	113.6
1988	118.3
1989	124.0
1990	130.7
1991	136.2
1992	140.3
1993	144.5
1994	148.2
1995	152.4
1996	156.9
1997	160.5
1998	163.0
1999	166.6
2000	172.2
2001	177.1
2002	179.9
2003	184.0
2004	188.9
2005	195.3
2006	201.6
2007	207.342
2008	215.303
2009	214.537
2010	216.687	*Based on January 2010 only


[add comment]
Personal tools