├── README.md └── Graphs of the day ├── 2012-12-21-SP500.png ├── 2012-12-31-Krugmans-Plot.png ├── 2013-01-02-Mankiw-Fig-1-3.png ├── 2012-12-19-Mankiw-Figure-1-1.png ├── 2012-12-28-Mankiw-Figure-1-2.png ├── 2012-12-23-Real SP500 (Monthly).png ├── 2012-12-24-Demonstration-of-LLN.png ├── 2013-01-03-RBC-Utility-Surface.png ├── 2012-12-22-Zero-profits-with-CRTS.png ├── 2012-12-20-CRTS-production-frontier.png ├── 2012-12-23-Nominal SP500 (Monthly).png ├── 2012-12-24-Simulation-of-Differences.png ├── 2012-12-31-Constant-COE-Share-of-GDP.png ├── 2013-01-03-Optimal-Bundle-Period-0.png ├── 2013-01-03-Optimal-Bundle-Period-1.png ├── 2012-12-31-Declining-COE-Share-of-GDP.png ├── 2013-01-26-Solow-Residual-by-Income-Group.png ├── 2012-12-23-Real SP500 (Monthly, log-scale).png ├── 2013-01-03-RBC-Contour-Plot-Utility-Surface.png ├── 2012-12-22-Contour-plots-for-output-and-costs.png ├── 2012-12-22-Firm-size-indeterminate-with-CRTS.png ├── 2012-12-23-Nominal SP500 (Monthly, log-scale).png ├── 2012-12-24-Replication-of-Kerrich-experiment.png ├── 2013-01-01-Global-Inflation-by-Income-Groups.png ├── 2012-12-24-Kerrich-difference-btw-observed-expected-heads.png ├── Kerrich.txt ├── 2012-12-21.py ├── NBER Dates.txt ├── 2012-12-19.py ├── 2013-01-02.py ├── 2012-12-28.py ├── 2012-12-31.py ├── 2012-12-20.py ├── 2013-01-01.py ├── 2012-12-23.py ├── 2012-12-24.py ├── 2013-01-26.py ├── 2012-12-22.py └── 2013-01-03.py /README.md: -------------------------------------------------------------------------------- 1 | beyond-microfoundations 2 | ======================= 3 | 4 | Repository for code from my blog... -------------------------------------------------------------------------------- /Graphs of the day/2012-12-21-SP500.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2012-12-21-SP500.png -------------------------------------------------------------------------------- /Graphs of the day/2012-12-31-Krugmans-Plot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2012-12-31-Krugmans-Plot.png -------------------------------------------------------------------------------- /Graphs of the day/2013-01-02-Mankiw-Fig-1-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2013-01-02-Mankiw-Fig-1-3.png -------------------------------------------------------------------------------- /Graphs of the day/2012-12-19-Mankiw-Figure-1-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2012-12-19-Mankiw-Figure-1-1.png -------------------------------------------------------------------------------- /Graphs of the day/2012-12-28-Mankiw-Figure-1-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2012-12-28-Mankiw-Figure-1-2.png -------------------------------------------------------------------------------- /Graphs of the day/2012-12-23-Real SP500 (Monthly).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2012-12-23-Real SP500 (Monthly).png -------------------------------------------------------------------------------- /Graphs of the day/2012-12-24-Demonstration-of-LLN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2012-12-24-Demonstration-of-LLN.png -------------------------------------------------------------------------------- /Graphs of the day/2013-01-03-RBC-Utility-Surface.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2013-01-03-RBC-Utility-Surface.png -------------------------------------------------------------------------------- /Graphs of the day/2012-12-22-Zero-profits-with-CRTS.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2012-12-22-Zero-profits-with-CRTS.png -------------------------------------------------------------------------------- /Graphs of the day/2012-12-20-CRTS-production-frontier.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2012-12-20-CRTS-production-frontier.png -------------------------------------------------------------------------------- /Graphs of the day/2012-12-23-Nominal SP500 (Monthly).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2012-12-23-Nominal SP500 (Monthly).png -------------------------------------------------------------------------------- /Graphs of the day/2012-12-24-Simulation-of-Differences.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2012-12-24-Simulation-of-Differences.png -------------------------------------------------------------------------------- /Graphs of the day/2012-12-31-Constant-COE-Share-of-GDP.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2012-12-31-Constant-COE-Share-of-GDP.png -------------------------------------------------------------------------------- /Graphs of the day/2013-01-03-Optimal-Bundle-Period-0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2013-01-03-Optimal-Bundle-Period-0.png -------------------------------------------------------------------------------- /Graphs of the day/2013-01-03-Optimal-Bundle-Period-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2013-01-03-Optimal-Bundle-Period-1.png -------------------------------------------------------------------------------- /Graphs of the day/2012-12-31-Declining-COE-Share-of-GDP.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2012-12-31-Declining-COE-Share-of-GDP.png -------------------------------------------------------------------------------- /Graphs of the day/2013-01-26-Solow-Residual-by-Income-Group.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2013-01-26-Solow-Residual-by-Income-Group.png -------------------------------------------------------------------------------- /Graphs of the day/2012-12-23-Real SP500 (Monthly, log-scale).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2012-12-23-Real SP500 (Monthly, log-scale).png -------------------------------------------------------------------------------- /Graphs of the day/2013-01-03-RBC-Contour-Plot-Utility-Surface.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2013-01-03-RBC-Contour-Plot-Utility-Surface.png -------------------------------------------------------------------------------- /Graphs of the day/2012-12-22-Contour-plots-for-output-and-costs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2012-12-22-Contour-plots-for-output-and-costs.png -------------------------------------------------------------------------------- /Graphs of the day/2012-12-22-Firm-size-indeterminate-with-CRTS.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2012-12-22-Firm-size-indeterminate-with-CRTS.png -------------------------------------------------------------------------------- /Graphs of the day/2012-12-23-Nominal SP500 (Monthly, log-scale).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2012-12-23-Nominal SP500 (Monthly, log-scale).png -------------------------------------------------------------------------------- /Graphs of the day/2012-12-24-Replication-of-Kerrich-experiment.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2012-12-24-Replication-of-Kerrich-experiment.png -------------------------------------------------------------------------------- /Graphs of the day/2013-01-01-Global-Inflation-by-Income-Groups.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2013-01-01-Global-Inflation-by-Income-Groups.png -------------------------------------------------------------------------------- /Graphs of the day/2012-12-24-Kerrich-difference-btw-observed-expected-heads.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/beyond-microfoundations/master/Graphs of the day/2012-12-24-Kerrich-difference-btw-observed-expected-heads.png -------------------------------------------------------------------------------- /Graphs of the day/Kerrich.txt: -------------------------------------------------------------------------------- 1 | Tosses,Heads,Difference 2 | 10,4,-1 3 | 20,10,0 4 | 30,17,2 5 | 40,21,1 6 | 50,25,0 7 | 60,29,-1 8 | 70,32,-3 9 | 80,35,-5 10 | 90,40,-5 11 | 100,44,-6 12 | 200,98,-2 13 | 300,146,-4 14 | 400,199,-1 15 | 500,255,5 16 | 600,312,12 17 | 700,368,18 18 | 800,413,13 19 | 900,458,8 20 | 1000,502,2 21 | 2000,1013,13 22 | 3000,1510,10 23 | 4000,2029,29 24 | 5000,2533,33 25 | 6000,3009,9 26 | 7000,3516,16 27 | 8000,4034,34 28 | 9000,4538,38 29 | 10000,5067,67 30 | -------------------------------------------------------------------------------- /Graphs of the day/2012-12-21.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import matplotlib.pyplot as plt 3 | from pandas.io.data import get_data_yahoo 4 | 5 | ##### download data from Yahoo ##### 6 | 7 | # Download the S&P 500 8 | SP500 = get_data_yahoo('^GSPC', start='1950-01-03') 9 | 10 | ##### plot the data ##### 11 | 12 | # plot the S&P 500 index 13 | ax1 = SP500['Close'].plot() 14 | 15 | # add labels, axes, title, etc 16 | ax1.set_ylabel('Close') 17 | ax1.set_yscale('log') 18 | ax1.set_title('Historical S&P 500 Index', weight='bold') 19 | 20 | # load the NBER recession dates 21 | NBER_Dates = pd.read_csv('NBER Dates.txt') 22 | 23 | # for loop generates recession bands! 24 | for i in range(NBER_Dates.shape[0]): 25 | ax1.axvspan(NBER_Dates['Peak'][i], NBER_Dates['Trough'][i], facecolor='grey', alpha=0.5) 26 | 27 | # save the figure and display 28 | 29 | plt.savefig('2012-12-21-SP500.png') 30 | plt.show() 31 | -------------------------------------------------------------------------------- /Graphs of the day/NBER Dates.txt: -------------------------------------------------------------------------------- 1 | Peak,Trough 2 | 1857-06-01,1858-12-01 3 | 1860-10-01,1861-06-01 4 | 1865-04-01,1867-12-01 5 | 1869-06-01,1870-12-01 6 | 1873-10-01,1879-03-01 7 | 1882-03-01,1885-05-01 8 | 1887-03-01,1888-04-01 9 | 1890-07-01,1891-05-01 10 | 1893-01-01,1894-06-01 11 | 1895-12-01,1897-06-01 12 | 1899-06-01,1900-12-01 13 | 1902-09-01,1904-08-01 14 | 1907-05-01,1908-06-01 15 | 1910-01-01,1912-01-01 16 | 1913-01-01,1914-12-01 17 | 1918-08-01,1919-03-01 18 | 1920-01-01,1921-07-01 19 | 1923-05-01,1924-07-01 20 | 1926-10-01,1927-11-01 21 | 1929-08-01,1933-03-01 22 | 1937-05-01,1938-06-01 23 | 1945-02-01,1945-10-01 24 | 1948-11-01,1949-10-01 25 | 1953-07-01,1954-05-01 26 | 1957-08-01,1958-04-01 27 | 1960-04-01,1961-02-01 28 | 1969-12-01,1970-11-01 29 | 1973-11-01,1975-03-01 30 | 1980-01-01,1980-07-01 31 | 1981-07-01,1982-11-01 32 | 1990-07-01,1991-03-01 33 | 2001-03-01,2001-11-01 34 | 2007-12-01,2009-06-01 35 | -------------------------------------------------------------------------------- /Graphs of the day/2012-12-19.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import matplotlib.pyplot as plt 3 | from pandas.io.data import get_data_fred 4 | 5 | ##### download data from FRED ##### 6 | 7 | # Real GDP per capita (2010 Dollars, annual, NSA) 8 | USARGDPC = get_data_fred('USARGDPC', start='1960-01-01') 9 | 10 | ##### plot the data ##### 11 | 12 | # basic plot in one line of code! 13 | ax = USARGDPC.plot(legend=False) 14 | 15 | # add labels, axes, title, etc 16 | ax.set_ylabel("2010 U.S. Dollars") 17 | ax.set_yscale('log') 18 | ax.set_ylim(8000, 64000) 19 | ax.set_yticks([8000, 16000, 32000, 64000]) 20 | ax.set_yticklabels([8000, 16000, 32000, 64000]) 21 | ax.set_title("Real GDP per Person in the United States (USARGDPC)\nSource: U.S. Department of Labor, BLS (via FRED)", weight='bold') 22 | ax.grid() 23 | 24 | # load the NBER recession dates 25 | NBER_Dates = pd.read_csv('NBER Dates.txt') 26 | 27 | # for loop generates recession bands! 28 | for i in range(NBER_Dates.shape[0]): 29 | ax.axvspan(NBER_Dates['Peak'][i], NBER_Dates['Trough'][i], facecolor='grey', alpha=0.5) 30 | 31 | # save the figure and display 32 | plt.savefig('2012-12-19-Mankiw-Figure-1-1.png') 33 | plt.show() 34 | -------------------------------------------------------------------------------- /Graphs of the day/2013-01-02.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import matplotlib.pyplot as plt 3 | from pandas.io.data import get_data_fred 4 | 5 | def NBER_Shade(): 6 | """Function adds National Bureau of Economic Research (NBER) recession 7 | bands to a Matplotlib Figure object. 8 | 9 | """ 10 | 11 | # load the NBER recession dates 12 | NBER_Dates = pd.read_csv('NBER Dates.txt') 13 | 14 | # for loop generates recession bands! 15 | for i in range(NBER_Dates.shape[0]): 16 | plt.axvspan(NBER_Dates['Peak'][i], NBER_Dates['Trough'][i], 17 | facecolor='grey', alpha=0.5) 18 | 19 | ##### download data from FRED ##### 20 | 21 | # Civilian unemployment rate (monthly, SA) 22 | UNRATE_monthly = get_data_fred('UNRATE', start='1948-01-01') 23 | 24 | # Convert to annual frequency by averaging across months 25 | UNRATE_annual = UNRATE_monthly.resample('A', how='mean') 26 | 27 | ##### plot the historical unemployment rate ##### 28 | 29 | # basic plot in one line of code! 30 | UNRATE_annual.plot() 31 | 32 | # add labels, axes, title, etc 33 | plt.xlabel("Year") 34 | plt.ylabel("Percent") 35 | plt.ylim(0, 10) 36 | plt.title("Civilian unemployment rate (UNRATE), Seasonally adjusted\n" +\ 37 | "Source: U.S. Department of Labor, BLS (via FRED)", 38 | weight='bold') 39 | plt.grid() 40 | 41 | # add NBER recession bands 42 | NBER_Shade() 43 | 44 | # save the figure and display 45 | plt.savefig('2013-01-02-Mankiw-Fig-1-3.png') 46 | plt.show() 47 | -------------------------------------------------------------------------------- /Graphs of the day/2012-12-28.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import matplotlib.pyplot as plt 3 | from pandas.io.data import get_data_fred 4 | 5 | ##### download data from FRED ##### 6 | 7 | # Consumer Price Index for All Urban Consumers: All Items (Monthly, SA) 8 | CPIAUCSL = get_data_fred('CPIAUCSL', start='1947-01-01') 9 | 10 | # Consumer Price Index for All Urban Consumers: All Items (Monthly, NSA) 11 | CPIAUCNS = get_data_fred('CPIAUCNS', start='1913-01-01') 12 | 13 | # Gross Domestic Product: Implicit Price Deflator (Quarterly, SA) 14 | GDPDEF = get_data_fred('GDPDEF', start='1947-01-01') 15 | 16 | ##### Construct measures of inflation ##### 17 | 18 | # Inflation is measured as percentage change from one year ago 19 | Inflation_CPIAUCSL = CPIAUCSL.pct_change(periods=12) 20 | Inflation_CPIAUCNS = CPIAUCNS.pct_change(periods=12) 21 | Inflation_GDPDEF = GDPDEF.pct_change(periods=4) 22 | 23 | # Combine the three Series objects into a single DataFrame 24 | Inflation_Measures = Inflation_CPIAUCNS 25 | Inflation_Measures['CPIAUCSL'] = Inflation_CPIAUCSL 26 | Inflation_Measures['GDPDEF'] = Inflation_GDPDEF 27 | 28 | ##### plot the data ##### 29 | 30 | # basic plot in one line of code! 31 | Inflation_Measures.plot(markersize=3, style='o-', alpha=0.75) 32 | 33 | # add labels, axes, title, etc 34 | plt.ylabel("Inflation (% Change from a year ago)") 35 | plt.title("Measures of historical inflation in the U.S\nSource: U.S. Department of Labor, BLS (via FRED)", 36 | weight='bold') 37 | plt.grid() 38 | 39 | # load the NBER recession dates 40 | NBER_Dates = pd.read_csv('NBER Dates.txt') 41 | 42 | # for loop generates recession band!s 43 | for i in range(NBER_Dates.shape[0]): 44 | plt.axvspan(NBER_Dates['Peak'][i], NBER_Dates['Trough'][i], facecolor='grey', alpha=0.5) 45 | 46 | # save the figure and display 47 | plt.savefig('2012-12-28-Mankiw-Figure-1-2.png') 48 | plt.show() 49 | -------------------------------------------------------------------------------- /Graphs of the day/2012-12-31.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import matplotlib.pyplot as plt 3 | from pandas.io.data import get_data_fred 4 | 5 | def NBER_Shade(): 6 | """Function adds National Bureau of Economic Research (NBER) recession 7 | bands to a Matplotlib Figure object. 8 | 9 | """ 10 | 11 | # load the NBER recession dates 12 | NBER_Dates = pd.read_csv('NBER Dates.txt') 13 | 14 | # for loop generates recession bands! 15 | for i in range(NBER_Dates.shape[0]): 16 | plt.axvspan(NBER_Dates['Peak'][i], NBER_Dates['Trough'][i], 17 | facecolor='grey', alpha=0.5) 18 | 19 | ##### download data from FRED ##### 20 | 21 | # National Income: Compensation of Employees, Paid 22 | COE = get_data_fred('COE', start='1947-01-01') 23 | 24 | # Gross Domestic Product, 1 Decimal 25 | GDP = get_data_fred('GDP', start='1947-01-01') 26 | 27 | # combine into a DataFrame 28 | data = pd.concat([COE, GDP], axis=1) 29 | 30 | ##### Construct measure of labor's share ##### 31 | 32 | # Divide COE by GDP 33 | COE_share = data['COE'] / data['GDP'] 34 | 35 | ##### plot the data with auto-ajusted ylim ##### 36 | 37 | # basic plot in one line of code! 38 | COE_share.plot() 39 | 40 | # add labels, axes, title, etc 41 | plt.ylabel("COE Share") 42 | plt.title("Employee compensation share of U.S. GDP\n" +\ 43 | "Source: U.S. Department of Commerce, BEA (via FRED)", 44 | weight='bold') 45 | plt.grid() 46 | 47 | # add NBER recession bands 48 | NBER_Shade() 49 | 50 | # save the figure and display 51 | plt.savefig('2012-12-31-Declining-COE-Share-of-GDP.png') 52 | plt.show() 53 | 54 | ##### plot the data with auto-ajusted ylim ##### 55 | 56 | # basic plot in one line of code! (Krugman plots only data after 1973) 57 | COE_share['1973-01-01':].plot() 58 | 59 | # add labels, axes, title, etc 60 | plt.ylabel("COE Share") 61 | plt.title("Employee compensation share of U.S. GDP\n" +\ 62 | "Source: U.S. Department of Commerce, BEA (via FRED)", 63 | weight='bold') 64 | plt.grid() 65 | 66 | # add the NBER recession bands 67 | NBER_Shade() 68 | 69 | # save the figure and display 70 | plt.savefig('2012-12-31-Krugmans-Plot.png') 71 | plt.show() 72 | 73 | ##### plot the data with auto-ajusted ylim ##### 74 | 75 | # basic plot in one line of code! 76 | labors_share.plot() 77 | 78 | # add labels, axes, title, etc 79 | plt.ylabel(r"COE Share") 80 | plt.ylim(0, 1) 81 | plt.title("Employee compensation share of U.S. GDP\n" +\ 82 | "Source: U.S. Department of Commerce, BEA (via FRED)", 83 | weight='bold') 84 | plt.grid() 85 | 86 | # add the NBER recession bands! 87 | NBER_Shade() 88 | 89 | # save the figure and display 90 | plt.savefig('2012-12-31-Constant-COE-Share-of-GDP.png') 91 | plt.show() 92 | -------------------------------------------------------------------------------- /Graphs of the day/2012-12-20.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib as mpl 3 | import matplotlib.pyplot as plt 4 | from mpl_toolkits.mplot3d import Axes3D 5 | 6 | # define the Cobb-Douglas production function 7 | def F(K, L, A=1): 8 | """ 9 | 10 | Classic Cobb-Douglas production function. Output is a function of the capital 11 | stock, K, and labor, L. Note that technology, A, is assumed to be labor- 12 | augmenting. 13 | 14 | Parameters, which are assumed to be already defined, are capital's share, 15 | alpha, and labor's share beta. Typically, one assumes constant returns to scale 16 | in which case beta = 1 - alpha. 17 | 18 | """ 19 | return K**alpha * (A * L)**beta 20 | 21 | # create a grid of (x,y) values which we will pass to function 22 | capital = np.linspace(0, 50, 100) 23 | labor = np.linspace(0, 50, 100) 24 | K, L = np.meshgrid(capital, labor) 25 | 26 | # Choose parameter values 27 | alpha = 1 / 3. 28 | beta = 1 - alpha 29 | A = 1 30 | 31 | # we will actually plot output 32 | output = F(K, L, A) 33 | 34 | ##### Static snapshot using matplotlib ##### 35 | 36 | # create a new Figure object 37 | fig = plt.figure(figsize=(12,6)) 38 | 39 | # create a 3D Axes object for the first subplot 40 | ax = fig.add_subplot(121, projection='3d', elev=30, azim=310) 41 | 42 | # note the use of the new plot command! 43 | production_frontier = ax.plot_surface(K, L, output, rstride=1, cstride=1, cmap=mpl.cm.hot, 44 | linewidth=0, vmin=0, vmax=np.max(output), 45 | antialiased=False) 46 | 47 | # axes, labels, title, colorbar etc. 48 | ax.set_xlim(0, 50) 49 | ax.set_ylim(0, 50) 50 | ax.set_xlabel(r'Capital ($K_{t}$)') 51 | ax.set_ylabel(r'Labor ($L_{t}$)') 52 | 53 | # create the contour plot for the second subplot 54 | ax2 = fig.add_subplot(122) 55 | im = ax2.imshow(output, interpolation='gaussian', origin='lower', cmap=mpl.cm.hot, 56 | vmin=0, vmax=np.max(output), extent=(0, 50, 0, 50)) 57 | 58 | # demarcate the contours 59 | CS = ax2.contour(K, L, output, np.linspace(0, np.max(output), 10), colors=np.repeat('k', 10), 60 | linewidths=1, linestyles='solid') 61 | ax2.clabel(CS, inline=1, fmt='%1.2f') 62 | 63 | # axes, labels, title, colorbar etc. 64 | ax2.set_xlim(0, 50) 65 | ax2.set_ylim(0, 50) 66 | ax2.set_xlabel(r'Capital, $K_{t}$') 67 | ax2.set_ylabel(r'Labor, $L_{t}$') 68 | 69 | # add a color bar to the figure 70 | fig.colorbar(production_frontier, shrink=0.75, aspect=10) 71 | 72 | # add a title to the figure 73 | fig.text(0.5, 0.95, r'$F(K,\ L)=K^{\alpha}(AL)^{1 - \alpha}$ for $\alpha=%.2f, A=%.2f$' %(alpha, A), fontsize=20, \ 74 | ha='center') 75 | 76 | # save the plot! 77 | plt.savefig('2012-12-20-CRTS-production-frontier.png') 78 | 79 | # display the plot! 80 | plt.show() 81 | 82 | """ 83 | ##### Interactive production frontier using Mayavi ##### 84 | from mayavi import mlab 85 | 86 | # plot the data using mayavi 87 | production_frontier = mlab.mesh(K, L, output, colormap='hot') 88 | 89 | # add axes 90 | axes = mlab.axes(xlabel=r'Capital, K', ylabel=r'Labor, L', zlabel=r'Output, Y') 91 | 92 | # display the interactive plot 93 | mlab.show() 94 | 95 | """ 96 | -------------------------------------------------------------------------------- /Graphs of the day/2013-01-01.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | import matplotlib.cm as cm 5 | import wbdata 6 | 7 | ##### Extract data from World Bank API ##### 8 | 9 | # Want to grab measure of inflation (for comparison purposes) 10 | indicators = {"FP.CPI.TOTL.ZG": "value"} 11 | 12 | # Low income countries 13 | LIC_countries = [country['id'] for country in wbdata.get_country(incomelevel="LIC", display=False)] 14 | LIC_df = wbdata.get_dataframe(indicators, country=LIC_countries, convert_date=False) 15 | 16 | # Lower Middle income countries 17 | LMC_countries = [country['id'] for country in wbdata.get_country(incomelevel="LMC", display=False)] 18 | LMC_df = wbdata.get_dataframe(indicators, country=LMC_countries, convert_date=False) 19 | 20 | # Upper Middle income countries 21 | UMC_countries = [country['id'] for country in wbdata.get_country(incomelevel="UMC", display=False)] 22 | UMC_df = wbdata.get_dataframe(indicators, country=UMC_countries, convert_date=False) 23 | 24 | # High income countries 25 | HIC_countries = [country['id'] for country in wbdata.get_country(incomelevel="HIC", display=False)] 26 | HIC_df = wbdata.get_dataframe(indicators, country=HIC_countries, convert_date=False) 27 | 28 | ##### plot FP.CPI.TOTL.ZG #### 29 | fig = plt.figure(figsize=(12,8)) 30 | ax = fig.add_subplot(111) 31 | 32 | # add LIC inflation data 33 | for country in np.unique(LIC_df['country'].values): 34 | # extract subset for given country 35 | mask = (LIC_df['country'] == country) 36 | tmp_data = LIC_df[mask] 37 | 38 | # plot inflation data 39 | LIC_plot, = ax.plot(tmp_data['date'].values, tmp_data['value'].values, 40 | color=cm.jet(0), alpha = 0.25) 41 | # Label the LICs 42 | LIC_plot.set_label('Low') 43 | 44 | # add LMC inflation data 45 | for country in np.unique(LMC_df['country'].values): 46 | # extract subset for given country 47 | mask = (LMC_df['country'] == country) 48 | tmp_data = LMC_df[mask] 49 | 50 | # plot inflation data 51 | LMC_plot, = ax.plot(tmp_data['date'].values, tmp_data['value'].values, 52 | color=cm.jet(85), alpha = 0.25) 53 | # Label the LMC plot 54 | LMC_plot.set_label('Lower-Middle') 55 | 56 | # add UMC inflation data 57 | for country in np.unique(UMC_df['country'].values): 58 | # extract subset for given country 59 | mask = (UMC_df['country'] == country) 60 | tmp_data = UMC_df[mask] 61 | 62 | # plot inflation data 63 | UMC_plot, = ax.plot(tmp_data['date'].values, tmp_data['value'].values, 64 | color=cm.jet(170), alpha = 0.25) 65 | # Label the UMC plot 66 | UMC_plot.set_label('Upper-Middle') 67 | 68 | # add HIC countries 69 | for country in np.unique(HIC_df['country'].values): 70 | # extract subset for given country 71 | mask = (HIC_df['country'] == country) 72 | tmp_data = HIC_df[mask] 73 | 74 | # plot inflation data 75 | HIC_plot, = ax.plot(tmp_data['date'].values, tmp_data['value'].values, 76 | color=cm.jet(255), alpha = 0.25) 77 | # Label the HIC plot 78 | HIC_plot.set_label('High') 79 | 80 | # axes, labels, title, legend, etc 81 | ax.set_xlabel('Year') 82 | ax.set_xlim(1960, 2012) 83 | ax.set_ylabel("Inflation, consumer prices (annual %)") 84 | ax.set_yscale('symlog') 85 | ax.set_title('Global Inflation by Income Group\nSource: World Bank, WDI', 86 | weight='bold', fontsize=15) 87 | ax.legend(loc=3, frameon=False, ncol=5, mode="expand") 88 | 89 | # save the figure and display... 90 | plt.savefig('2013-01-01-Global-Inflation-by-Income-Groups.png') 91 | plt.show() 92 | -------------------------------------------------------------------------------- /Graphs of the day/2012-12-23.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import matplotlib.pyplot as plt 3 | from pandas.io.data import get_data_yahoo, get_data_fred 4 | 5 | ##### download data ##### 6 | 7 | # Download the S&P 500 8 | SP500 = get_data_yahoo('^GSPC', start='1950-01-03', end='2012-11-30') 9 | 10 | # Download the CPI data 11 | CPIAUCSL = get_data_fred('CPIAUCSL', start='1950-01-01') 12 | 13 | ##### resample S&P 500 data ##### 14 | 15 | # Need S&P 500 data to be monthly...note I am taking monthly averages 16 | monthly_avg_SP500 = SP500.resample('MS', how='mean') 17 | 18 | # Add the CPI data as a column to the monthly DataFrame 19 | monthly_avg_SP500['CPIAUCSL'] = CPIAUCSL 20 | 21 | ##### Convert nominal values to real values ##### 22 | 23 | # express all prices in terms of the price level in Nov. 2012... 24 | monthly_avg_SP500['Price Deflator'] = (monthly_avg_SP500['CPIAUCSL']['2012-11-01'] / monthly_avg_SP500['CPIAUCSL']) 25 | monthly_avg_SP500['Close (Real)'] = monthly_avg_SP500['Close'] * monthly_avg_SP500['Price Deflator'] 26 | 27 | ##### Nominal S&P 500 ##### 28 | 29 | # new figure 30 | fig = plt.figure() 31 | 32 | # plot the nominal S&P 500 index 33 | ax = monthly_avg_SP500['Close'].plot() 34 | 35 | # add labels, axes, title, etc 36 | ax.set_ylabel('Close') 37 | ax.set_title('Historical S&P 500 Index (Monthly Avg.)', weight='bold') 38 | 39 | # load the NBER recession dates 40 | NBER_Dates = pd.read_csv('NBER Dates.txt') 41 | 42 | # for loop generates recession bands! 43 | for i in range(NBER_Dates.shape[0]): 44 | ax.axvspan(NBER_Dates['Peak'][i], NBER_Dates['Trough'][i], facecolor='grey', alpha=0.5) 45 | 46 | # save the figure and display 47 | plt.savefig('2012-12-23-Nominal SP500 (Monthly).png') 48 | plt.show() 49 | 50 | ##### Nominal S&P 500 (log-scale) ##### 51 | 52 | # new figure 53 | fig = plt.figure() 54 | 55 | # plot the nominal S&P 500 index 56 | ax = monthly_avg_SP500['Close'].plot() 57 | 58 | # add labels, axes, title, etc 59 | ax.set_ylabel('Close') 60 | ax.set_yscale('log') 61 | ax.set_title('Historical S&P 500 Index (Monthly Avg.)', weight='bold') 62 | 63 | # load the NBER recession dates 64 | NBER_Dates = pd.read_csv('NBER Dates.txt') 65 | 66 | # for loop generates recession bands! 67 | for i in range(NBER_Dates.shape[0]): 68 | ax.axvspan(NBER_Dates['Peak'][i], NBER_Dates['Trough'][i], facecolor='grey', alpha=0.5) 69 | 70 | # save the figure and display 71 | plt.savefig('2012-12-23-Nominal SP500 (Monthly, log-scale).png') 72 | plt.show() 73 | 74 | ##### Real S&P 500 ##### 75 | 76 | # new figure 77 | fig = plt.figure() 78 | 79 | # plot the nominal S&P 500 index 80 | ax = monthly_avg_SP500['Close (Real)'].plot() 81 | 82 | # add labels, axes, title, etc 83 | ax.set_ylabel('Close (Nov. 2012 Dollars)') 84 | ax.set_title('Historical S&P 500 Index (Monthly Avg.)', weight='bold') 85 | 86 | # load the NBER recession dates 87 | NBER_Dates = pd.read_csv('NBER Dates.txt') 88 | 89 | # for loop generates recession bands! 90 | for i in range(NBER_Dates.shape[0]): 91 | ax.axvspan(NBER_Dates['Peak'][i], NBER_Dates['Trough'][i], facecolor='grey', alpha=0.5) 92 | 93 | # save the figure and display 94 | plt.savefig('2012-12-23-Real SP500 (Monthly).png') 95 | plt.show() 96 | 97 | ##### Real S&P 500 (log-scale) ##### 98 | 99 | # new figure 100 | fig = plt.figure() 101 | 102 | # plot the real S&P 500 index 103 | ax = monthly_avg_SP500['Close (Real)'].plot() 104 | 105 | # add labels, axes, title, etc 106 | ax.set_ylabel('Close (Nov. 2012 Dollars)') 107 | ax.set_yscale('log') 108 | ax.set_title('Historical S&P 500 Index (Monthly Avg.)', weight='bold') 109 | 110 | # load the NBER recession dates 111 | NBER_Dates = pd.read_csv('NBER Dates.txt') 112 | 113 | # for loop generates recession bands! 114 | for i in range(NBER_Dates.shape[0]): 115 | ax.axvspan(NBER_Dates['Peak'][i], NBER_Dates['Trough'][i], facecolor='grey', alpha=0.5) 116 | 117 | # save the figure and display 118 | plt.savefig('2012-12-23-Real SP500 (Monthly, log-scale).png') 119 | plt.show() 120 | -------------------------------------------------------------------------------- /Graphs of the day/2012-12-24.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | from scipy import stats 4 | import matplotlib as mpl 5 | import matplotlib.pyplot as plt 6 | 7 | # load the kerrich data 8 | kerrich_data = pd.read_csv('Kerrich.txt', header=0, index_col=0) 9 | 10 | # create an object representing a fair coin 11 | fair_coin = stats.distributions.bernoulli(0.5) 12 | 13 | ##### Difference between observed and expected heads is diverging ##### 14 | 15 | # create new Figure and Axes objects 16 | fig = plt.figure() 17 | ax = fig.add_subplot(111) 18 | 19 | # plot Kerrich's difference 20 | kerrich_data['Difference'].plot(style='r-', label='Kerrich Data') 21 | 22 | # axes, labels, title, legend, etc. 23 | ax.set_xscale('log') 24 | ax.set_xlabel('Index') 25 | ax.set_ylabel('Observed heads - expected heads') 26 | ax.set_title('Divergence between observed heads and expected heads?') 27 | ax.legend(loc='best', frameon=False) 28 | 29 | # save the figure and display! 30 | plt.savefig('2012-12-24-Kerrich-difference-btw-observed-expected-heads.png') 31 | plt.show() 32 | 33 | ##### Checking Kerrich (single replication) ##### 34 | 35 | # simulate 10000 flips of a fair coin 36 | T = 10000 37 | np.random.seed(42) 38 | data = fair_coin.rvs((T,)) 39 | 40 | # compute the difference between the observed and expected number of heads 41 | difference = np.array([ 2 * np.sum(data[:i + 1]) - (i + 1) for i in range(T) ]) 42 | 43 | # create new Figure and Axes objects 44 | fig = plt.figure() 45 | ax = fig.add_subplot(111) 46 | 47 | # plot the experimental data... 48 | ax.plot(np.arange(1, 10001, 1), difference, 'k-', alpha=0.75) 49 | 50 | # plot Kerrich's observed difference 51 | kerrich_data['Difference'].plot(style='r-', label='Kerrich Data') 52 | 53 | # axes, labels, title, legend, etc. 54 | ax.set_xscale('log') 55 | ax.set_xlabel('Index') 56 | ax.set_ylabel('Observed heads - expected heads') 57 | ax.set_title("A single replication of Kerrich's experiment!") 58 | ax.legend(loc='best', frameon=False) 59 | 60 | # save the figure and display 61 | plt.savefig('2012-12-24-Replication-of-Kerrich-experiment.png') 62 | plt.show() 63 | 64 | ##### N replications of the Kerrich experiment ##### 65 | 66 | # N runs, each of length T 67 | N = 100 68 | T = 10000 69 | 70 | # generate an array of integers (each of n columns can be interpreted as a run of length T) 71 | data = fair_coin.rvs((T,N)) 72 | 73 | # create an array in which to store the results 74 | difference = np.zeros(data.shape, dtype=float) 75 | 76 | # double for loop conducts the experiment 77 | for j in range(N): 78 | for i in range(T): 79 | difference[i, j] = 2 * np.sum(data[:i + 1, j]) - (i + 1) 80 | 81 | # create new Figure and Axes objects 82 | fig = plt.figure() 83 | ax = fig.add_subplot(111) 84 | 85 | # plot each sample path... 86 | for i in range(N): 87 | ax.plot(np.arange(1, T + 1, 1), difference[:, i], 'k-', alpha=0.05) 88 | 89 | # plot Kerrich's observed difference 90 | kerrich_data['Difference'].plot(style='r-', label='Kerrich Data') 91 | 92 | # axes, labels, title, legend, etc. 93 | ax.set_xscale('log') 94 | ax.set_xlabel('Index') 95 | ax.set_ylabel('Observed heads - expected heads') 96 | ax.set_title("Kerrich's result was typical!") 97 | ax.legend(loc='best', frameon=False) 98 | 99 | # save the figure and display! 100 | plt.savefig('2012-12-24-Simulation-of-Differences.png') 101 | plt.show() 102 | 103 | ##### Show that the LLN holds #### 104 | 105 | # set params 106 | N = 100 107 | T = 10000 108 | 109 | # generate an array of integers (each of n columns can be interpreted as a run of length T) 110 | data = fair_coin.rvs((T,N)) 111 | 112 | # create an array in which to store our sample averages 113 | sample_averages = np.zeros(data.shape, dtype=float) 114 | 115 | for j in range(N): 116 | for i in range(T): 117 | sample_averages[i, j] = np.mean(data[:i + 1, j]) 118 | 119 | # determine the fraction of heads in the kerrich data 120 | kerrich_data['Fraction Heads'] = kerrich_data['Heads'] / kerrich_data.index.values.astype('float') 121 | 122 | # create new Figure and Axes objects 123 | fig = plt.figure() 124 | ax = fig.add_subplot(111) 125 | 126 | # plot each sample path 127 | for i in range(N): 128 | ax.plot(np.arange(1, T + 1, 1), sample_averages[:, i], 'k-', alpha=0.05) 129 | 130 | # plot Kerrich's fraction of heads 131 | kerrich_data['Fraction Heads'].plot(style='r-', label=r'$\hat{\mu}_{k}$') 132 | 133 | # demarcate the true mean 134 | ax.axhline(y=0.5, color='black', linestyle='dashed', label=r'$\mu$') 135 | 136 | # axes, labels, title, legend, etc. 137 | ax.set_xscale('log') 138 | ax.set_ylim(0, 1) 139 | ax.set_xlabel('Index') 140 | ax.set_ylabel(r'$\hat{\mu}$', rotation='horizontal', fontsize=15) 141 | ax.set_title(r'Average number of heads converges to $\mu=0.5$!') 142 | ax.legend(loc='best', frameon=False) 143 | 144 | # save the figure and display the plot 145 | plt.savefig('2012-12-24-Demonstration-of-LLN.png') 146 | plt.show() 147 | -------------------------------------------------------------------------------- /Graphs of the day/2013-01-26.py: -------------------------------------------------------------------------------- 1 | import zipfile 2 | from urllib import urlopen 3 | from StringIO import StringIO 4 | 5 | import numpy as np 6 | import pandas as pd 7 | import wbdata as wb 8 | import matplotlib.pyplot as plt 9 | import matplotlib as mpl 10 | 11 | def get_SolowResiduals(rgdppc, rgdppw, g0, delta, alpha, h=10, **kwargs): 12 | """Computes Solow residuals! 13 | 14 | Required arguments: 15 | 16 | 1. rgdppc: Must specify a valid measure of real gdp per capita. 17 | Valid options are rgdpl, rgdpl2, rgdpch. See Penn World 18 | Tables documentation for definitions of these variables. 19 | 2. rgdppw: Must specify a valid measure of real gdp per worker. 20 | Valid options are rgdpwok, rgdpl2wok, rgdpl2pe, rgdpl2te. 21 | See Penn World Tables documentation for definitions of 22 | these variables. 23 | 3. g0: Initial guess for the growth rate of technology. 24 | Required in order to pin down an initial estimate of the 25 | capital stock. 26 | 4. delta: Estimated rate of capital decpreciation rate. 27 | Required in order to compute the capital stock. 28 | 5. alpha: Estimated share of income/output going to capital. 29 | Required in order to decompose the growth rates in order to 30 | impute A and g. 31 | 6. h (default=10): Must specify the amount of smoothing to be 32 | applied to computed growth rates (i.e., those of labor 33 | force, investment share, and technology). 34 | 35 | """ 36 | 37 | # optional keywords args 38 | path = kwargs.get('path', None) 39 | version = kwargs.get('version', 71) 40 | date = kwargs.get('date', '11302012') 41 | extract = kwargs.get('extract', True) 42 | 43 | # first check for a local copy of PWT 44 | if path != None: 45 | pwt = pd.read_csv(path, index_col=['year', 'isocode']) 46 | 47 | # otherwise, download the appropriate zip file 48 | elif path == None: 49 | url = 'http://pwt.econ.upenn.edu/Downloads/pwt' + \ 50 | str(version) + '/pwt' + str(version) +'_' + date + \ 51 | 'version.zip' 52 | archive = zipfile.ZipFile(StringIO(urlopen(url).read()), 'r') 53 | 54 | # to extract or not to extract... 55 | tmp_file = 'pwt' + str(version) + \ 56 | '_wo_country_names_wo_g_vars.csv' 57 | if extract == True: 58 | archive.extractall() 59 | pwt = pd.read_csv(tmp_file, index_col=['year', 'isocode']) 60 | else: 61 | pwt = archive.read(tmp_file) 62 | pwt = pd.read_csv(StringIO(pwt), index_col=['year', 'isocode']) 63 | 64 | # convert to Pandas Panel object 65 | pwt = pwt.to_panel() 66 | 67 | # to compute Solow residuals need to a measure of real GDP... 68 | pwt['realGDP'] = pwt[rgdppc] * pwt.POP 69 | 70 | # ...and a measure of labor force growth rates 71 | pwt['laborForce'] = (pwt[rgdppc] / pwt[rgdppw]) * pwt.POP 72 | pwt['laborForceGrowth'] = pwt.laborForce.pct_change() 73 | 74 | # annual growth rates are noisy, smooth them! Note backshift! 75 | tmp_data = pd.rolling_mean(pwt.laborForceGrowth, 76 | window=10, min_periods=h).shift(-h) 77 | pwt['smoothedLaborForceGrowth'] = tmp_data 78 | 79 | # convert ki to proportion 80 | pwt['investmentShare'] = pwt.ki / 100. 81 | 82 | # investment shares are also noisy, smooth them! Note backshift! 83 | tmp_data = pd.rolling_mean(pwt.investmentShare, window=10, 84 | min_periods=h).shift(-h) 85 | pwt['smoothedInvestmentShare'] = tmp_data 86 | 87 | # initial data on imputed K is just made up of K0 (and junk!) 88 | break_even_s = (1 + pwt.smoothedLaborForceGrowth) * (1 + g0) - (1 - delta) 89 | actual_s = pwt.smoothedInvestmentShare 90 | pwt['imputedK'] = pwt.realGDP * (actual_s / break_even_s) 91 | 92 | # impute capital stock for each country 93 | for ctry, value in pwt.imputedK.iteritems(): 94 | for year in pwt.imputedK.index[:-1]: # no data beyond 2010 95 | if np.isnan(value.ix[year]) == False: 96 | k = pwt.imputedK[ctry].ix[year] 97 | s = pwt.investmentShare[ctry].ix[year] 98 | y = pwt.realGDP[ctry].ix[year] 99 | k_plus = (1 - delta) * k + s * y 100 | pwt.imputedK[ctry].ix[year + 1] = k_plus 101 | else: 102 | pass 103 | 104 | # create capital-output ratio 105 | pwt['capitalOutputRatio'] = pwt.imputedK / pwt.realGDP 106 | 107 | # compute the implied level of technology 108 | pwt['technology'] = pwt[rgdppw] / (pwt.capitalOutputRatio**(alpha / (1 - alpha))) 109 | 110 | # finally, compute the growth in technology 111 | pwt['technologyGrowth'] = pwt['technology'].pct_change() 112 | 113 | return pwt 114 | 115 | # Use the above function to grab the PWT data 116 | g0, delta, alpha = 0.02, 0.05, 0.33 117 | data = get_SolowResiduals(rgdppc='rgdpl', rgdppw='rgdpwok', 118 | g0=g0, delta=delta, alpha=alpha) 119 | 120 | ##### Divide countries into income groups ##### 121 | 122 | # Low income countries 123 | LIC_countries = [country['id'] for country in \ 124 | wb.get_country(incomelevel="LIC", display=False)] 125 | 126 | # Lower Middle income countries 127 | LMC_countries = [country['id'] for country in \ 128 | wb.get_country(incomelevel="LMC", display=False)] 129 | 130 | # Upper Middle income countries 131 | UMC_countries = [country['id'] for country in \ 132 | wb.get_country(incomelevel="UMC", display=False)] 133 | 134 | # High income countries 135 | HIC_countries = [country['id'] for country in \ 136 | wb.get_country(incomelevel="HIC", display=False)] 137 | 138 | ##### Plot technology (i.e., the Solow resiual) ##### 139 | # plot the level of technology 140 | fig = plt.figure(figsize=(8,8)) 141 | 142 | # color scheme 143 | colors = mpl.cm.jet(np.linspace(0, 1, 4), alpha=0.25) 144 | 145 | for ctry in data.minor_axis: 146 | if ctry in LIC_countries: 147 | data['technology'][ctry].plot(color=colors[0], legend=False) 148 | elif ctry in LMC_countries: 149 | data['technology'][ctry].plot(color=colors[1], legend=False) 150 | elif ctry in UMC_countries: 151 | data['technology'][ctry].plot(color=colors[2], legend=False) 152 | elif ctry in HIC_countries: 153 | data['technology'][ctry].plot(color=colors[3], legend=False) 154 | 155 | val = data['technology'][ctry].ix[2010] 156 | if np.isnan(val) == False: 157 | plt.text(2010, val , ctry, fontsize=8) 158 | 159 | # Axes, labels, title, etc 160 | plt.yscale('log') 161 | plt.ylabel('Technology, A', fontsize=15) 162 | plt.xlabel('Year', fontsize=15) 163 | plt.title(r'Technology by income group ($g_0$=%.2f, $\delta$=%.2f, $\alpha$=%.2f)' % (g0,delta,alpha), 164 | fontsize=15) 165 | 166 | plt.savefig('2013-01-26-Solow-Residual-by-Income-Group.png') 167 | plt.show() 168 | -------------------------------------------------------------------------------- /Graphs of the day/2012-12-22.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib as mpl 3 | import matplotlib.pyplot as plt 4 | from mpl_toolkits.mplot3d import Axes3D 5 | 6 | # define the Cobb-Douglas production function 7 | def F(K, L, A=1): 8 | """ 9 | 10 | Classic Cobb-Douglas production function. Output is a function of the capital 11 | stock, K, and labor, L. Note that technology, A, is assumed to be labor- 12 | augmenting. 13 | 14 | Parameters, which are assumed to be already defined, are capital's share, 15 | alpha, and labor's share beta. Typically, one assumes constant returns to scale 16 | in which case beta = 1 - alpha. 17 | 18 | """ 19 | return K**alpha * (A * L)**beta 20 | 21 | # define a function for the real wage 22 | def real_wage(K, L, A=1): 23 | """ 24 | 25 | Assuming perfect competition, factors are paid there marginal products. Thus 26 | the real wage paid to labor is dF/dL. 27 | 28 | """ 29 | MPL = (1 - alpha) * K**alpha * (A * L)**(-alpha) * A 30 | return MPL 31 | 32 | # define a function for the return to capital 33 | def return_capital(K, L, A=1): 34 | """ 35 | 36 | Assuming perfect competition, factors are paid there marginal products. Thus 37 | the real return to capital is dF/dK. 38 | 39 | """ 40 | MPK = alpha * K**(alpha - 1) * (A * L)**(1 - alpha) 41 | return MPK 42 | 43 | # define the expansion path from MPK and MPL 44 | def expansion_path(K): 45 | """ 46 | 47 | Set of tangency points between isocost lines and isoquants. 48 | 49 | """ 50 | return ((1 - alpha) / alpha) * (r / w) * K 51 | 52 | # define the cost function 53 | def C(K, L): 54 | """ 55 | 56 | Two sources of costs: labor costs, wL, and rental costs of capital, rK. 57 | 58 | """ 59 | return w * L + r * K 60 | 61 | def Pi(K, L, A): 62 | """ 63 | 64 | Profits function from firm's maximization problem. 65 | 66 | """ 67 | return F(K, L, A) - C(K, L) 68 | 69 | # create a grid of (x,y) values which we will pass to function 70 | capital = np.linspace(0, 50, 100) 71 | labor = np.linspace(0, 50, 100) 72 | K, L = np.meshgrid(capital, labor) 73 | 74 | # Choose parameter values 75 | alpha = 1 / 3. 76 | beta = 1 - alpha 77 | A = 1.0 78 | w, r = real_wage(2, 1), return_capital(2, 1) 79 | 80 | # we will eventually plot... 81 | output = F(K, L, A) 82 | costs = C(K, L) 83 | profits = Pi(K, L, A) 84 | 85 | ##### Contour plots for output and costs ##### 86 | 87 | # create a new Figure object 88 | fig = plt.figure(figsize=(12,6)) 89 | 90 | # create the contour plot for the second subplot 91 | ax1 = fig.add_subplot(121) 92 | production_surface = ax1.imshow(output, interpolation='gaussian', origin='lower', cmap=mpl.cm.hot, 93 | vmin=0, vmax=np.max(output), extent=(0, 50, 0, 50)) 94 | 95 | # demarcate the contours 96 | CS = ax1.contour(K, L, output, np.linspace(0, 50, 10), colors=np.repeat('k', 10), 97 | linewidths=1, linestyles='solid') 98 | ax1.clabel(CS, inline=1, fmt='%1.2f') 99 | 100 | # axes, labels, title, colorbar etc. 101 | ax1.set_xlim(0, 50) 102 | ax1.set_ylim(0, 50) 103 | ax1.set_xlabel(r'Capital, $K$') 104 | ax1.set_ylabel(r'Labor, $L$') 105 | 106 | # create the contour plot for cost function 107 | ax2 = fig.add_subplot(122) 108 | cost_surface = ax2.imshow(costs, interpolation='gaussian', origin='lower', cmap=mpl.cm.cool, \ 109 | vmin=0, vmax=np.max(costs), extent=(0, 50, 0, 50)) 110 | 111 | # demarcate the contours 112 | CS = ax2.contour(K, L, costs, np.linspace(0, 50, 10), colors=np.repeat('k', 10), 113 | linewidths=1, linestyles='solid') 114 | ax2.clabel(CS, inline=1, fmt='%1.2f') 115 | 116 | # axes, labels, title, colorbar etc. 117 | ax2.set_xlim(0, 50) 118 | ax2.set_ylim(0, 50) 119 | ax2.set_xlabel(r'Capital, $K$') 120 | ax2.set_ylabel(r'Labor, $L$') 121 | 122 | fig.text(0.5, 0.95, 'Isoquants and isocosts lines for CRTS Cobb-Douglas production function', 123 | fontsize=20, ha='center') 124 | 125 | # Save figure 126 | plt.savefig('2012-12-22-Contour-plots-for-output-and-costs.png') 127 | 128 | # display plot 129 | plt.show() 130 | 131 | ##### Firm Size is indeterminate with CRTS ##### 132 | 133 | # create a new Figure object 134 | fig = plt.figure(figsize=(8,8)) 135 | 136 | # create the contour plot for the second subplot 137 | ax1 = fig.add_subplot(111) 138 | 139 | # demarcate the contours 140 | CS_output = ax1.contour(K, L, output, np.linspace(0, 50, 10), cmap=mpl.cm.hot, 141 | vmin=0, vmax=np.max(output), linewidths=1, linestyles='solid') 142 | ax1.clabel(CS_output, inline=1, fmt='%1.2f') 143 | 144 | CS_costs = ax1.contour(K, L, costs, np.linspace(0, 50, 10), cmap=mpl.cm.cool, 145 | vmin=0, vmax=np.max(costs), linewidths=1, linestyles='solid') 146 | 147 | # add the expansion path 148 | ax1.plot(capital, expansion_path(capital), 'k', label=r'$\frac{K}{L}$') 149 | 150 | # axes, labels, title, colorbar etc. 151 | ax1.set_xlim(0, 50) 152 | ax1.set_ylim(0, 50) 153 | ax1.set_xlabel(r'Capital, $K$') 154 | ax1.set_ylabel(r'Labor, $L$') 155 | ax1.set_title(r'With CRTS, firm size is indeterminate!', weight='bold') 156 | ax1.legend(loc='upper right', bbox_to_anchor=(1.15, 1.0), frameon=False) 157 | 158 | # Save figure 159 | plt.savefig('2012-12-22-Firm-size-indeterminate-with-CRTS.png') 160 | 161 | plt.show() 162 | 163 | ##### Profits surface and contour plot ##### 164 | 165 | # create a new Figure object 166 | fig = plt.figure(figsize=(12,6)) 167 | 168 | # create a 3D Axes object for the first subplot 169 | ax = fig.add_subplot(121, projection='3d', elev=30, azim=-120) 170 | 171 | # note the use of the new plot command! 172 | profits_surface = ax.plot_surface(K, L, profits, rstride=1, cstride=1, cmap=mpl.cm.winter_r, 173 | linewidth=0, vmin=np.min(profits), vmax=0, antialiased=False) 174 | 175 | # axes, labels, title, colorbar etc. 176 | ax.set_xlim(0, 50) 177 | ax.set_ylim(0, 50) 178 | ax.set_xlabel(r'Capital, $K$') 179 | ax.set_ylabel(r'Labor, $L$') 180 | ax.set_zlabel(r'Profits, $\Pi$') 181 | 182 | # create the contour plot for the second subplot 183 | ax2 = fig.add_subplot(122) 184 | im = ax2.imshow(profits, interpolation='gaussian', origin='lower', cmap=mpl.cm.winter_r, 185 | vmin=np.min(profits), vmax=0, extent=(0, 50, 0, 50)) 186 | 187 | # demarcate the contours 188 | CS = ax2.contour(K, L, profits, np.linspace(np.min(profits), 0, 10), colors=np.repeat('k', 10), 189 | linewidths=1, linestyles='solid') 190 | ax2.clabel(CS, inline=1, fmt='%1.2f') 191 | 192 | # add the expansion path (i.e., the zero contour!) 193 | zero_contour = ax2.plot(capital, expansion_path(capital), 'k', label=r'$\frac{K}{L}$') 194 | 195 | # axes, labels, title, colorbar etc. 196 | ax2.set_xlim(0, 50) 197 | ax2.set_ylim(0, 50) 198 | ax2.set_xlabel(r'Capital, $K$') 199 | ax2.set_ylabel(r'Labor, $L$') 200 | 201 | # add a color bar to the figure 202 | fig.colorbar(profits_surface, shrink=0.75, aspect=10) 203 | 204 | # add a title to the figure 205 | fig.text(0.5, 0.95, 'Firms earn zero profits in equilibrium', fontsize=20, ha='center') 206 | 207 | # save the plot! 208 | plt.savefig('2012-12-22-Zero-profits-with-CRTS.png') 209 | 210 | # display the plot! 211 | plt.show() 212 | -------------------------------------------------------------------------------- /Graphs of the day/2013-01-03.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy import linalg 3 | import matplotlib.pyplot as plt 4 | import matplotlib as mpl 5 | from mpl_toolkits.mplot3d import Axes3D 6 | 7 | # Define the representative agent's single period utility function 8 | def u(C, l): 9 | """In the standard RBC model utility in each period is a function 10 | of consumption per person, C, and leisure per person, 1 - l. Note 11 | that the worker's labor endowment has been normalized to 1 for 12 | simplicity. 13 | 14 | The parameter, b, determines how the representative agent weights 15 | uility from leisure relative to utility from consumption. 16 | 17 | """ 18 | return np.log(C) + b * np.log(1 - l) 19 | 20 | ##### Plot of the utility surface ##### 21 | 22 | # create a new Figure object 23 | fig = plt.figure(figsize=(8,6)) 24 | 25 | # create a 3D Axes object 26 | ax = fig.gca(projection='3d', elev=30, azim=310) 27 | 28 | # create a grid of (x,y) values which we will pass to function 29 | consumption = np.linspace(0, 10, 200) 30 | labor = np.linspace(0, 1, 20) 31 | l, C = np.meshgrid(labor, consumption) 32 | 33 | # Choose parameter values 34 | b = 2.5 35 | 36 | # we will actually plot output 37 | utility = u(C, l) 38 | 39 | # note the use of the new plot command! 40 | utility_surface = ax.plot_surface(l, C, utility, rstride=1, cstride=1, 41 | cmap=mpl.cm.terrain, linewidth=0, 42 | vmin=-10, vmax=np.max(utility), 43 | antialiased=False) 44 | 45 | # axes, labels, title, colorbar etc. 46 | ax.set_xlim(0, 1) 47 | ax.set_ylim(0, 10) 48 | ax.set_xlabel(r'Labor, $l_{t}$') 49 | ax.set_ylabel(r'Consumption, $C_{t}$') 50 | ax.set_title(r"Agent's utility surface, $u(C,\ l)$ for $b=%.2f$" %b, 51 | fontsize=20) 52 | fig.colorbar(utility_surface, shrink=0.75, aspect=10) 53 | 54 | # save the figure and display! 55 | plt.savefig('2013-01-03-RBC-Utility-Surface.png') 56 | plt.show() 57 | 58 | ##### Contour plot of the utility surface ##### 59 | fig = plt.figure(figsize=(8,8)) 60 | ax = fig.add_subplot(111) 61 | 62 | # Choose parameter values 63 | b = 2.5 64 | 65 | # we will actually plot output 66 | utility = u(C, l) 67 | 68 | # create the contour plot 69 | im = ax.imshow(utility, interpolation='gaussian', origin='lower', 70 | cmap=mpl.cm.terrain, vmin=-10, vmax=np.max(utility), 71 | extent=(0, 1, 0, 10), aspect=0.10) 72 | 73 | # demarcate the contours... 74 | CS = ax.contour(l, C, utility, np.linspace(-8, np.max(utility), 10), 75 | colors=np.repeat('k', 10), linewidths=1, 76 | linestyles='solid') 77 | ax.clabel(CS, inline=1, fmt='%1.2f') 78 | 79 | # axes, labels, title, colorbar etc. 80 | ax.set_xlim(0, 1) 81 | ax.set_ylim(0, 10) 82 | ax.set_xlabel(r'Labor, $l_{t}$') 83 | ax.set_ylabel(r'Consumption, $C_{t}$') 84 | ax.set_title(r'$u(C,\ l)$ for $b=%.2f$' %b, fontsize=20) 85 | fig.colorbar(utility_surface, shrink=0.75, aspect=10) 86 | 87 | # save figure and display 88 | plt.savefig('2013-01-03-RBC-Contour-Plot-Utility-Surface.png') 89 | plt.show() 90 | 91 | ##### Solving a 2-period model ##### 92 | 93 | # define parameter values 94 | b, beta = 2.5, 0.99 95 | 96 | # Specify some prices (i.e., wages and interest rates) all of which 97 | # households take as given when solving their optimization problem 98 | w0, w1, r1 = 5.0, 9.0, 0.025 99 | 100 | # Calculate the household's initial net worth (i.e., the PDV of his 101 | # labor endowment) given these prices 102 | networth = w0 + (1 / (1 + r1)) * w1 103 | print "PDV of Household's net worth:", networth 104 | 105 | # is the non-negativity constraint on l0 satisfied by chosen prices? 106 | print (1 / (1 + r1)) * (w1 / w0) < ((((1 + b) * (1 + beta)) / b) - 1) 107 | 108 | # is the non-negativity constraint on l1 satisfied by chosen prices? 109 | print (1 + r1) * (w0 / w1) < (((1 + b) / b) * ((1 + beta) / beta) - 1) 110 | 111 | # define system of linear equations in four unknowns: C0, l0, C1, l1 112 | A = np.array([[b, 0, w0, 0], 113 | [beta * (1 + r1), -1, 0, 0], 114 | [0, b, 0, w1], 115 | [1, 1 / (1 + r1), -w0, -(1 / (1 + r1)) * w1]]) 116 | 117 | d = np.array([[w0], 118 | [0], 119 | [w1], 120 | [0]]) 121 | 122 | # Solve the system of equations and assign the optimal choices for 123 | # consumption and labor supply 124 | C_star0 = linalg.solve(A, d)[0,0] 125 | C_star1 = linalg.solve(A, d)[1,0] 126 | l_star0 = linalg.solve(A, d)[2,0] 127 | l_star1 = linalg.solve(A, d)[3,0] 128 | u_star0 = u(C_star0, l_star0) 129 | u_star1 = u(C_star1, l_star1) 130 | 131 | print "Optimal C sequence:", (C_star0, C_star1) 132 | print "Optimal l sequence:", (l_star0, l_star1) 133 | print "Flow of utility: ", (u_star0, u_star1) 134 | 135 | ##### Plotting the optimal bundle in period t=0 #### 136 | fig = plt.figure(figsize=(8,8)) 137 | ax = fig.add_subplot(111) 138 | 139 | # we will actually plot output 140 | utility = u(C, l) 141 | 142 | # re-create the contour plot 143 | im = ax.imshow(utility, interpolation='gaussian', origin='lower', 144 | cmap=mpl.cm.terrain, vmin=-10, vmax=np.max(utility), 145 | extent=(0, 1, 0, 10), aspect=0.10) 146 | 147 | # plot the budget constraint 148 | labor_supply = np.linspace(0, 1, 100) 149 | ax.plot(labor_supply, w0 * labor_supply + (1 / (1 + r1)) * \ 150 | (w1 * l_star1 - C_star1), color='r', 151 | label=r'$C_{0}=w_{0}l_{0} + \frac{1}{1 + r_{1}}(w_{1}l_{1}^* - C_{1}^*)$') 152 | 153 | # demarcate the indifference curve... 154 | CS = ax.contour(l, C, utility, np.array([u_star0]), colors='k', 155 | linewidths=1, linestyles='solid') 156 | ax.clabel(CS, inline=1, fmt='%1.4f') 157 | 158 | # mark the optimal bundle 159 | ax.hlines(C_star0, 0, l_star0, linestyle='dashed') 160 | ax.vlines(l_star0, 0, C_star0, linestyle='dashed') 161 | 162 | # axes, labels, title, colorbar etc. 163 | ax.set_xlim(0, 1) 164 | ax.set_ylim(0, 10) 165 | ax.set_ylabel(r'Consumption, $C_{t}$') 166 | ax.set_xlabel(r'Labor, $l_{t}$') 167 | ax.set_title(r'Optimal bundle in period t=0 for $b=%.2f, \beta=%.2f$' 168 | %(b, beta), fontsize=15) 169 | ax.legend(loc=4, frameon=False) 170 | fig.colorbar(utility_surface, shrink=0.75, aspect=10) 171 | 172 | # Save the figure and display 173 | plt.savefig('2013-01-03-Optimal-Bundle-Period-0.png') 174 | plt.show() 175 | 176 | ##### Plotting the optimal bundle in period t=1 ##### 177 | 178 | fig = plt.figure(figsize=(8,8)) 179 | ax = fig.add_subplot(111) 180 | 181 | # we will actually plot output 182 | utility = u(C, l) 183 | 184 | # re-create the contour plot 185 | im = ax.imshow(utility, interpolation='gaussian', origin='lower', 186 | cmap=mpl.cm.terrain, vmin=-10, vmax=np.max(utility), 187 | extent=(0, 1, 0, 10), aspect=0.10) 188 | 189 | # plot the budget constraint 190 | labor_supply = np.linspace(0, 1, 100) 191 | ax.plot(labor_supply, w0 * labor_supply + (1 / (1 + r1)) * \ 192 | (w1 * l_star1 - C_star1), color='r', alpha=0.25) 193 | ax.plot(labor_supply, w1 * labor_supply + (1 + r1) * \ 194 | (w0 * l_star0 - C_star0), color='r', 195 | label=r'$C_{1} = w_{1}l_{1} + (1 + r_{1})(w_{0}l_{0}^* - C_{0}^*)$') 196 | 197 | # demarcate the indifference curve... 198 | CS_0 = ax.contour(l, C, utility, np.array([u_star0]), colors='k', 199 | linewidths=1, linestyles='solid', alpha=0.25) 200 | CS_1 = ax.contour(l, C, utility, np.array([u_star1]), colors='k', 201 | linewidths=1, linestyles='solid') 202 | ax.clabel(CS_1, inline=1, fmt='%1.4f') 203 | 204 | # mark the optimal bundle 205 | ax.hlines(C_star1, 0, l_star1, linestyle='dashed') 206 | ax.vlines(l_star1, 0, C_star1, linestyle='dashed') 207 | 208 | # axes, labels, title, colorbar etc. 209 | ax.set_xlim(0, 1) 210 | ax.set_ylim(0, 10) 211 | ax.set_ylabel(r'Consumption, $C_{t}$') 212 | ax.set_xlabel(r'Labor, $l_{t}$') 213 | ax.set_title(r'Optimal bundle in period t=1 for $b=%.2f, \beta=%.2f$' \ 214 | %(b, beta), fontsize=15) 215 | ax.legend(loc=4, frameon=False) 216 | fig.colorbar(utility_surface, shrink=0.75, aspect=10) 217 | 218 | # Save the figure and display 219 | plt.savefig('2013-01-03-Optimal-Bundle-Period-1.png') 220 | plt.show() 221 | --------------------------------------------------------------------------------