├── .github ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── build_and_test.yml │ ├── check_format.yml │ ├── deploy_docs.yml │ └── docs_check.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── Makefile ├── README.md ├── code ├── AdvancedNumPy │ └── advanced_numpy.py ├── Exceptions_FileIO │ ├── cf_example1.txt │ ├── cf_example2.txt │ ├── exceptions_fileIO.py │ └── hello_world.txt ├── Matplotlib1 │ ├── FARS.npy │ └── matplotlib_intro.py ├── Matplotlib2 │ └── matplotlib2.ipynb ├── Matplotlib3 │ └── animation.ipynb ├── NumPyIntro │ ├── grid.npy │ └── numpy_intro.py ├── ObjectOriented │ └── object_oriented.py ├── Pandas1 │ └── pandas1.ipynb ├── Pandas3 │ └── pandas3.ipynb ├── PythonIntro │ └── python_intro.py ├── StandardLibrary │ ├── box.py │ └── standard_library.py ├── StrEstPaper │ └── LaTeXtemplates │ │ ├── LaTeX_projtemplate.bib │ │ ├── LaTeX_projtemplate.pdf │ │ ├── LaTeX_projtemplate.tex │ │ ├── LaTeX_slides.pdf │ │ ├── LaTeX_slides.tex │ │ └── images │ │ └── ability_log_2D.png ├── UnitTest │ ├── specs.py │ └── test_specs.py ├── UnixShell1 │ ├── Shell1.zip │ └── unixshell1.sh ├── gmm │ └── distributions.py ├── junk_funcs.py └── mle │ └── distributions.py ├── data ├── Matplotlib3 │ └── orbits.npz ├── Pandas1 │ ├── DJIA.csv │ ├── budget.csv │ ├── crime_data.csv │ └── paychecks.csv ├── Pandas3 │ ├── Ohio_1999.csv │ ├── college.csv │ ├── mammal_sleep.csv │ └── titanic.csv ├── basic_empirics │ ├── Auto.csv │ ├── logit │ │ ├── titanic-train.csv │ │ └── titanic_clean.csv │ └── maketable1.dta ├── basic_ml │ └── Hitters.csv ├── gmm │ ├── Econ381totpts.txt │ ├── MacroSeries.txt │ └── hh_inc_synth.txt ├── mle │ ├── Econ381totpts.txt │ ├── MacroSeries.txt │ └── claims.txt └── smm │ ├── Econ381totpts.txt │ ├── MacroSeries.txt │ ├── NewMacroSeries.txt │ ├── clms.txt │ └── usincmoms.txt ├── docs ├── .nojekyll ├── CompMethodsLogo.png ├── CompMethodsLogo_gitfig.png ├── CompMethodsLogo_horizontal.png ├── CompMethodsLogo_vertical.png ├── README.md ├── book │ ├── CompMethods_references.bib │ ├── CompMethods_references.md │ ├── _config.yml │ ├── _static │ │ └── custom.css │ ├── _toc.yml │ ├── appendix │ │ ├── appendix.md │ │ └── glossary.md │ ├── basic_empirics │ │ ├── BasicEmpirMethods.md │ │ └── LogisticReg.md │ ├── basic_ml │ │ └── ml_intro.md │ ├── conf.py │ ├── contrib │ │ └── contributing.md │ ├── deep_learn │ │ └── intro.md │ ├── git │ │ └── intro.md │ ├── images │ │ ├── Git │ │ │ └── GitFlowDiag.png │ │ ├── SciPy │ │ │ └── root_examp1.png │ │ ├── icon_GitHub.png │ │ ├── icon_background.png │ │ ├── icon_download.png │ │ ├── icon_fullscreen.png │ │ └── icon_search.png │ ├── index.md │ ├── python │ │ ├── DocStrings.md │ │ ├── ExceptionsIO.md │ │ ├── Matplotlib.md │ │ ├── NumPy.md │ │ ├── OOP.md │ │ ├── Pandas.md │ │ ├── SciPy.md │ │ ├── StandardLibrary.md │ │ ├── UnitTesting.md │ │ └── intro.md │ └── struct_est │ │ ├── GMM.md │ │ ├── MLE.md │ │ ├── SMM.md │ │ ├── intro.md │ │ └── paper.md └── favicon.ico ├── environment.yml ├── images ├── basic_empirics │ ├── basic_empirics │ │ ├── AcemogluEtAl_fig2.png │ │ ├── AcemogluEtAl_predvals.png │ │ ├── CorrVsCaus.png │ │ ├── scatter1.png │ │ ├── scatter2.png │ │ └── scatter3.png │ └── logit │ │ ├── Fig2_14.png │ │ ├── Fig2_15.png │ │ ├── Fig2_16.png │ │ ├── age_boxplot.png │ │ ├── logit_gen.png │ │ └── survived_count.png ├── gmm │ ├── Econ381Scores_SurfaceCrit4.png │ ├── Econ381scores_2MLEs.png │ ├── Econ381scores_4mom2mom.png │ ├── Econ381scores_SurfaceCrit1.png │ ├── Econ381scores_SurfaceCrit4_2.png │ └── hist_inc.png ├── mle │ ├── Econ381scores_2truncs.png │ ├── Econ381scores_MLE.png │ ├── Econ381scores_MLEconstr.png │ ├── Econ381scores_SurfaceLogLike.png │ ├── Econ381scores_SurfaceLogLikeZoom.png │ ├── Econ381scores_hist.png │ └── GBtree.png └── smm │ ├── Econ381_crit1.png │ ├── Econ381_crit4.png │ ├── Econ381scores_sim1.png │ ├── Econ381scores_smm1.png │ ├── Econ381scores_smm4_1.png │ └── Econ381scores_truncnorm.png ├── setup.py └── tests └── test_add_junk.py /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Thanks for filing an issue. Please consider including the following information in your issue. This will help us efficiently respond to the issue and incorporate its valuable components into the repository. Please delete this paragraph, and feel free to include any of the following content that you think is relevant. 2 | 3 | # Clear and concise title 4 | Please give this issue a clear and concise title that directly references the key point in your issue. 5 | 6 | # Problem or Error 7 | Please characterize the problem concisely and precisely. You may want to include error message output, other terminal output, your environment characteristics, and a way to replicate the issue. Let us know what solutions you have tried. You may also want to include a minimal reproducible example (MRE; see [this Stackoverflow tutorial](https://stackoverflow.com/help/minimal-reproducible-example) and this [Wikipedia page](https://en.wikipedia.org/wiki/Minimal_reproducible_example)). These types of examples are referred to in other coding cotexts as "minimal,complete, and verifiable example (MCVE)", "minimal workable example (MWE)", "reprex", and "short, self-contained correct example (SSCCE)". 8 | 9 | # Question 10 | Please ask the question with clear context and any potential answer directions you can think of. 11 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Thanks for contributing! Please remove any top-level sections that do not apply to your changes. 2 | 3 | - [ ] `make documentation`, `make format`, and `make test` have been run locally on my machine. 4 | 5 | ## What's changed 6 | 7 | Description of the changes here. Link any issues this PR fixes. 8 | -------------------------------------------------------------------------------- /.github/workflows/build_and_test.yml: -------------------------------------------------------------------------------- 1 | name: Build and test [Python 3.10, 3.11] 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ${{ matrix.os }} 8 | strategy: 9 | matrix: 10 | os: [ubuntu-latest, macos-latest, windows-latest] 11 | python-version: ["3.10", "3.11"] 12 | 13 | steps: 14 | - name: Checkout 15 | uses: actions/checkout@v4 16 | with: 17 | persist-credentials: false 18 | 19 | - name: Setup Miniconda using Python ${{ matrix.python-version }} 20 | uses: conda-incubator/setup-miniconda@v2 21 | with: 22 | miniforge-variant: Mambaforge 23 | auto-update-conda: true 24 | activate-environment: compmethods-dev 25 | environment-file: environment.yml 26 | python-version: ${{ matrix.python-version }} 27 | auto-activate-base: false 28 | 29 | - name: Build 30 | shell: bash -l {0} 31 | run: | 32 | pip install -e . 33 | pip install pytest-cov 34 | pip install pytest-pycodestyle 35 | - name: Test 36 | shell: bash -l {0} 37 | working-directory: ./ 38 | run: | 39 | pytest -m 'not local' --cov=./ --cov-report=xml 40 | - name: Upload coverage to Codecov 41 | uses: codecov/codecov-action@v3 42 | with: 43 | files: ./coverage.xml 44 | flags: unittests 45 | name: codecov-umbrella 46 | fail_ci_if_error: true 47 | verbose: true 48 | -------------------------------------------------------------------------------- /.github/workflows/check_format.yml: -------------------------------------------------------------------------------- 1 | 2 | name: Check code formatting 3 | 4 | on: [push, pull_request] 5 | 6 | jobs: 7 | lint: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v4 11 | - uses: actions/setup-python@v4 12 | - uses: psf/black@stable 13 | with: 14 | options: "-l 79 --check" 15 | src: "." 16 | -------------------------------------------------------------------------------- /.github/workflows/deploy_docs.yml: -------------------------------------------------------------------------------- 1 | name: Build and Deploy Jupyter Book documentation 2 | on: 3 | push: 4 | branches: 5 | - main 6 | jobs: 7 | build-and-deploy: 8 | if: github.repository == 'OpenSourceEcon/CompMethods' 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Checkout 12 | uses: actions/checkout@v4 13 | with: 14 | persist-credentials: false 15 | 16 | - name: Setup Miniconda 17 | uses: conda-incubator/setup-miniconda@v2 18 | with: 19 | miniforge-variant: Mambaforge 20 | activate-environment: compmethods-dev 21 | environment-file: environment.yml 22 | python-version: "3.10" 23 | auto-activate-base: false 24 | 25 | - name: Build # Build Jupyter Book 26 | shell: bash -l {0} 27 | run: | 28 | pip install -e . 29 | python -m ipykernel install --user --name=compmethods-dev 30 | cd docs 31 | jb build ./book 32 | 33 | - name: Deploy 34 | uses: JamesIves/github-pages-deploy-action@v4 35 | with: 36 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 37 | BRANCH: gh-pages # The branch the action should deploy to. 38 | FOLDER: docs/book/_build/html # The folder the action should deploy. 39 | -------------------------------------------------------------------------------- /.github/workflows/docs_check.yml: -------------------------------------------------------------------------------- 1 | name: Check that docs build 2 | on: [push, pull_request] 3 | 4 | jobs: 5 | build: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - name: Checkout 9 | uses: actions/checkout@v4 10 | with: 11 | persist-credentials: false 12 | 13 | - name: Setup Miniconda 14 | uses: conda-incubator/setup-miniconda@v2 15 | with: 16 | miniforge-variant: Mambaforge 17 | activate-environment: compmethods-dev 18 | environment-file: environment.yml 19 | python-version: "3.10" 20 | auto-activate-base: false 21 | 22 | - name: Build # Build Jupyter Book 23 | shell: bash -l {0} 24 | run: | 25 | pip install -e . 26 | python -m ipykernel install --user --name=compmethods-dev 27 | cd docs 28 | jb build ./book 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | MANIFEST 3 | build/* 4 | dist/* 5 | *.aux 6 | *.bbl 7 | *.blg 8 | *.fdb_latexmk 9 | *.idx 10 | *.ilg 11 | *.ind 12 | *.lof 13 | *.log 14 | *.lot 15 | *.out 16 | *.pdfsync 17 | *.synctex.gz 18 | *.toc 19 | *.swp 20 | *.asv 21 | *.nav 22 | *.snm 23 | *.gz 24 | *.bib.bak 25 | *.fls 26 | *.m~ 27 | *.sublime* 28 | .DS_Store 29 | *puf.csv 30 | */OUTPUT/* 31 | */__pycache__/* 32 | *.coverage* 33 | *.pytest* 34 | Icon? 35 | .ipynb_checkpoints/* 36 | 37 | # Built Jupyter-book documentation 38 | docs/book/_build 39 | 40 | # Backup docs 41 | pdfs/* 42 | 43 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [0.1.0] - 2023-12-15 17:00:00 9 | 10 | ### Added 11 | - Updates the Generalized Method of Moments chapter. 12 | - Adds a structural estimation paper chapter. 13 | - Adds other updates in the Structural Estimation section. 14 | 15 | ## [0.0.7] - 2023-12-06 15:00:00 16 | 17 | ### Added 18 | - Updates the Maximum Likelihood Estimation section. 19 | 20 | ## [0.0.6] - 2023-11-03 00:45:00 21 | 22 | ### Added 23 | - Updates the Basic Empirical Methods section 24 | 25 | ## [0.0.5] - 2023-10-27 05:00:00 26 | 27 | ### Added 28 | - Updates the Basic Empirical Methods section 29 | 30 | ## [0.0.4] - 2023-10-27 02:00:00 31 | 32 | ### Added 33 | - Updates the Python and Git chapters as well as the corresponding data, images, and code 34 | 35 | ## [0.0.3] - 2023-10-23 03:00:00 36 | 37 | ### Added 38 | - Updated the `SMM.md` chapter 39 | 40 | ## [0.0.2] - 2023-09-29 06:00:00 41 | 42 | ### Added 43 | - Updates the `SMM.md` and `GMM.md` chapters 44 | - Adds a `MaxLikelihood.md` chapter 45 | - Updates `CompMethods_references.bib` 46 | - Adds data files in `/data/smm/` directory 47 | 48 | ## [0.0.1] - 2023-09-28 18:30:00 49 | 50 | ### Added 51 | 52 | - Updated `README.md` and `setup.py` 53 | - Deleted `changelog.yaml` 54 | 55 | ## [0.0.0] - 2023-09-28 17:00:00 56 | 57 | ### Added 58 | 59 | - Created CompMethods repository at GitHub.com/OpenSourceEcon/CompMethods 60 | 61 | 62 | 63 | [0.1.0]: https://github.com/OpenSourceEcon/CompMethods/compare/v0.0.7...v0.1.0 64 | [0.0.7]: https://github.com/OpenSourceEcon/CompMethods/compare/v0.0.6...v0.0.7 65 | [0.0.6]: https://github.com/OpenSourceEcon/CompMethods/compare/v0.0.5...v0.0.6 66 | [0.0.5]: https://github.com/OpenSourceEcon/CompMethods/compare/v0.0.4...v0.0.5 67 | [0.0.4]: https://github.com/OpenSourceEcon/CompMethods/compare/v0.0.3...v0.0.4 68 | [0.0.3]: https://github.com/OpenSourceEcon/CompMethods/compare/v0.0.2...v0.0.3 69 | [0.0.2]: https://github.com/OpenSourceEcon/CompMethods/compare/v0.0.1...v0.0.2 70 | [0.0.1]: https://github.com/OpenSourceEcon/CompMethods/compare/v0.0.0...v0.0.1 71 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | format: 2 | black . -l 79 3 | linecheck . --fix 4 | install: 5 | pip install -e . 6 | test: 7 | pytest -m 'not local' 8 | documentation: 9 | jupyter-book clean docs/book 10 | jupyter-book build docs/book 11 | changelog: 12 | build-changelog changelog.yaml --output changelog.yaml --update-last-date --start-from 0.0.0 --append-file changelog_entry.yaml 13 | build-changelog changelog.yaml --org OpenSourceEcon --repo CompMeths --output CHANGELOG.md --template .github/changelog_template.md 14 | bump-version changelog.yaml setup.py 15 | rm changelog_entry.yaml || true 16 | touch changelog_entry.yaml 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # *Computational Methods for Economists using Python*, by Richard W. Evans 2 | 3 | | | | 4 | | --- | --- | 5 | | Org | [![OSE Lab cataloged](https://img.shields.io/badge/OSE%20Lab-catalogued-critical)](https://github.com/OpenSourceEcon) [![OS License: AGPL-3.0](https://img.shields.io/badge/OS%20License-AGPL%203.0-yellow)](https://github.com/OpenSourceEcon/CompMethods/blob/main/LICENSE) [![Jupyter Book Badge](https://jupyterbook.org/badge.svg)](https://opensourceecon.github.io/CompMethods/) | 6 | | Package | [![Python 3.10](https://img.shields.io/badge/python-3.10-blue.svg)](https://www.python.org/downloads/release/python-31013/) [![Python 3.11](https://img.shields.io/badge/python-3.11-blue.svg)](https://www.python.org/downloads/release/python-3115/) | 7 | | Testing | ![example event parameter](https://github.com/OpenSourceEcon/CompMethods/actions/workflows/build_and_test.yml/badge.svg?branch=main) ![example event parameter](https://github.com/OpenSourceEcon/CompMethods/actions/workflows/deploy_docs.yml/badge.svg?branch=main) ![example event parameter](https://github.com/OpenSourceEcon/CompMethods/actions/workflows/check_format.yml/badge.svg?branch=main) [![Codecov](https://codecov.io/gh/OpenSourceEcon/CompMethods/branch/main/graph/badge.svg)](https://codecov.io/gh/OpenSourceEcon/compmethods) | 8 | 9 | This repository contains the source material, code, and data for the book, [*Computational Methods for Economists using Python*](https://opensourceecon.github.io/CompMethods/), by Richard W. Evans (2023). This book is freely available online as an executable Jupyter Book at https://opensourceecon.github.io/CompMethods. 10 | 11 | The materials for the book are constantly being updated. The version number listed in the [Releases](https://github.com/OpenSourceEcon/CompMethods/releases) section of the repository tracks the updates, as well as the [`CHANGELOG.md`](CHANGELOG.md) file. 12 | 13 | As an open executable book project, this book is happy to receive, address, and incorporate collaborative additions, corrections, suggestions, and questions. Please see the [Contributor Guide](https://opensourceecon.github.io/CompMethods/contrib/contributing.html) in the book for how to best collaborate with the project. 14 | 15 | [Richard W. Evans, Phd](https://sites.google.com/site/rickecon) ([@rickecon](https://github.com/rickecon)) is the author of the book and the core maintainer of this repository. 16 | 17 | ## Citing this book 18 | Please use the following citation form for this book. 19 | 20 | General citation to the book: 21 | * Evans, Richard W., *Computational Methods for Economists using Python*, Open access Jupyter Book, v#.#.#, 2023, https://opensourceecon.github.io/CompMethods/. 22 | 23 | Citation to a chapter in the book only authored by Evans: 24 | * Evans, Richard W., "[insert chapter name]", in *Computational Methods for Economists using Python*, Open access Jupyter Book, v#.#.#, 2023, https://opensourceecon.github.io/CompMethods + [chapter path]. 25 | 26 | Citation to a chapter in the book only authored by multiple authors: 27 | * DeBacker, Jason and Richard W. Evans, "[insert chapter name]", in *Computational Methods for Economists using Python*, Open access Jupyter Book, v#.#.#, 2023, https://opensourceecon.github.io/CompMethods + [chapter path]. 28 | -------------------------------------------------------------------------------- /code/AdvancedNumPy/advanced_numpy.py: -------------------------------------------------------------------------------- 1 | # advanced_numpy.py 2 | """Python Essentials: Advanced NumPy. 3 | 4 | 5 | 6 | """ 7 | import numpy as np 8 | from sympy import isprime 9 | from matplotlib import pyplot as plt 10 | 11 | 12 | def prob1(A): 13 | """Make a copy of 'A' and set all negative entries of the copy to 0. 14 | Return the copy. 15 | 16 | Example: 17 | >>> A = np.array([-3,-1,3]) 18 | >>> prob4(A) 19 | array([0, 0, 3]) 20 | """ 21 | raise NotImplementedError("Problem 1 Incomplete") 22 | 23 | 24 | def prob2(arr_list): 25 | """return all arrays in arr_list as one 3-dimensional array 26 | where the arrays are padded with zeros appropriately.""" 27 | raise NotImplementedError("Problem 2 Incomplete") 28 | 29 | 30 | def prob3(func, A): 31 | """Time how long it takes to run func on the array A in two different ways, 32 | where func is a universal function. 33 | First, use array broadcasting to operate on the entire array element-wise. 34 | Second, use a nested for loop, operating on each element individually. 35 | Return the ratio showing how many times faster array broadcasting is than 36 | using a nested for loop, averaged over 10 trials. 37 | 38 | Parameters: 39 | func -- array broadcast-able numpy function 40 | A -- nxn array to operate on 41 | Returns: 42 | num_times_faster -- float 43 | """ 44 | raise NotImplementedError("Problem 3 Incomplete") 45 | 46 | 47 | def prob4(A): 48 | """Divide each row of 'A' by the row sum and return the resulting array. 49 | 50 | Example: 51 | >>> A = np.array([[1,1,0],[0,1,0],[1,1,1]]) 52 | >>> prob6(A) 53 | array([[ 0.5 , 0.5 , 0. ], 54 | [ 0. , 1. , 0. ], 55 | [ 0.33333333, 0.33333333, 0.33333333]]) 56 | """ 57 | raise NotImplementedError("Problem 4 Incomplete") 58 | 59 | 60 | # this is provided for problem 5 61 | def LargestPrime(x, show_factorization=False): 62 | # account for edge cases. 63 | if x == 0 or x == 1: 64 | return np.nan 65 | 66 | # create needed variables 67 | forced_break = False 68 | prime_factors = [] # place to store factors of number 69 | factor_test_arr = np.arange(1, 11) 70 | 71 | while True: 72 | # a factor is never more than half the number 73 | if np.min(factor_test_arr) > (x // 2) + 1: 74 | forced_break = True 75 | break 76 | if isprime(x): # if the checked number is prime itself, stop 77 | prime_factors.append(x) 78 | break 79 | 80 | # check if anythin gin the factor_test_arr are factors 81 | div_arr = x / factor_test_arr 82 | factor_mask = div_arr - div_arr.astype(int) == 0 83 | divisors = factor_test_arr[factor_mask] 84 | if divisors.size > 0: # if divisors exist... 85 | if ( 86 | divisors[0] == 1 and divisors.size > 1 87 | ): # make sure not to select 1 88 | i = 1 89 | elif ( 90 | divisors[0] == 1 and divisors.size == 1 91 | ): # if one is the only one don't pick it 92 | factor_test_arr = factor_test_arr + 10 93 | continue 94 | else: # othewise take the smallest divisor 95 | i = 0 96 | 97 | # if divisor was found divide number by it and 98 | # repeat the process 99 | x = int(x / divisors[i]) 100 | prime_factors.append(divisors[i]) 101 | factor_test_arr = np.arange(1, 11) 102 | else: # if no number was found increase the test_arr 103 | # and keep looking for factors 104 | factor_test_arr = factor_test_arr + 10 105 | continue 106 | 107 | if show_factorization: # show entire factorization if desired 108 | print(prime_factors) 109 | if forced_break: # if too many iterations break 110 | print(f"Something wrong, exceeded iteration threshold for value: {x}") 111 | return 0 112 | return max(prime_factors) 113 | 114 | 115 | def prob5(arr, naive=False): 116 | """Return an array where every number is replaced be the largest prime 117 | in its factorization. Implement two methods. Switching between the two 118 | is determined by a bool. 119 | 120 | Example: 121 | >>> A = np.array([15, 41, 49, 1077]) 122 | >>> prob4(A) 123 | array([5,41,7,359]) 124 | """ 125 | raise NotImplementedError("Problem 5 Incomplete") 126 | 127 | 128 | def prob6(x, y, z, A, optimize=False, split=True): 129 | """takes three vectors and a matrix and performs 130 | (np.outer(x,y)*z.reshape(-1,1))@A on them using einsum.""" 131 | raise NotImplementedError("Problem 6 part 1 Incomplete") 132 | 133 | 134 | def naive6(x, y, z, A): 135 | """uses normal numpy functions to do what prob5 does""" 136 | raise NotImplementedError("Problem 6 part 2 Incomplete") 137 | 138 | 139 | def prob7(): 140 | """Times and creates plots that generate the difference in 141 | speeds between einsum and normal numpy functions 142 | """ 143 | raise NotImplementedError("Problem 7 Incomplete") 144 | -------------------------------------------------------------------------------- /code/Exceptions_FileIO/cf_example1.txt: -------------------------------------------------------------------------------- 1 | A b C 2 | d E f 3 | -------------------------------------------------------------------------------- /code/Exceptions_FileIO/cf_example2.txt: -------------------------------------------------------------------------------- 1 | Ab Cd 2 | Ef Gh 3 | Ij Kl 4 | -------------------------------------------------------------------------------- /code/Exceptions_FileIO/exceptions_fileIO.py: -------------------------------------------------------------------------------- 1 | # exceptions_fileIO.py 2 | """Python Essentials: Exceptions and File Input/Output. 3 | 4 | 5 | 6 | """ 7 | 8 | from random import choice 9 | 10 | 11 | # Problem 1 12 | def arithmagic(): 13 | """ 14 | Takes in user input to perform a magic trick and prints the result. 15 | Verifies the user's input at each step and raises a 16 | ValueError with an informative error message if any of the following occur: 17 | 18 | The first number step_1 is not a 3-digit number. 19 | The first number's first and last digits differ by less than $2$. 20 | The second number step_2 is not the reverse of the first number. 21 | The third number step_3 is not the positive difference of the first two numbers. 22 | The fourth number step_4 is not the reverse of the third number. 23 | """ 24 | 25 | step_1 = input( 26 | "Enter a 3-digit number where the first and last " 27 | "digits differ by 2 or more: " 28 | ) 29 | step_2 = input( 30 | "Enter the reverse of the first number, obtained " 31 | "by reading it backwards: " 32 | ) 33 | step_3 = input("Enter the positive difference of these numbers: ") 34 | step_4 = input("Enter the reverse of the previous result: ") 35 | print(str(step_3), "+", str(step_4), "= 1089 (ta-da!)") 36 | 37 | 38 | # Problem 2 39 | def random_walk(max_iters=1e12): 40 | """ 41 | If the user raises a KeyboardInterrupt by pressing ctrl+c while the 42 | program is running, the function should catch the exception and 43 | print "Process interrupted at iteration $i$". 44 | If no KeyboardInterrupt is raised, print "Process completed". 45 | 46 | Return walk. 47 | """ 48 | 49 | walk = 0 50 | directions = [1, -1] 51 | for i in range(int(max_iters)): 52 | walk += choice(directions) 53 | return walk 54 | 55 | 56 | # Problems 3 and 4: Write a 'ContentFilter' class. 57 | class ContentFilter(object): 58 | """Class for reading in file 59 | 60 | Attributes: 61 | filename (str): The name of the file 62 | contents (str): the contents of the file 63 | 64 | """ 65 | 66 | # Problem 3 67 | def __init__(self, filename): 68 | """Read from the specified file. If the filename is invalid, prompt 69 | the user until a valid filename is given. 70 | """ 71 | 72 | # Problem 4 --------------------------------------------------------------- 73 | def check_mode(self, mode): 74 | """Raise a ValueError if the mode is invalid.""" 75 | 76 | def uniform(self, outfile, mode="w", case="upper"): 77 | """Write the data to the outfile with uniform case. Include an additional 78 | keyword argument case that defaults to "upper". If case="upper", write 79 | the data in upper case. If case="lower", write the data in lower case. 80 | If case is not one of these two values, raise a ValueError.""" 81 | 82 | def reverse(self, outfile, mode="w", unit="word"): 83 | """Write the data to the outfile in reverse order. Include an additional 84 | keyword argument unit that defaults to "line". If unit="word", reverse 85 | the ordering of the words in each line, but write the lines in the same 86 | order as the original file. If units="line", reverse the ordering of the 87 | lines, but do not change the ordering of the words on each individual 88 | line. If unit is not one of these two values, raise a ValueError.""" 89 | 90 | def transpose(self, outfile, mode="w"): 91 | """Write a transposed version of the data to the outfile. That is, write 92 | the first word of each line of the data to the first line of the new file, 93 | the second word of each line of the data to the second line of the new 94 | file, and so on. Viewed as a matrix of words, the rows of the input file 95 | then become the columns of the output file, and viceversa. You may assume 96 | that there are an equal number of words on each line of the input file. 97 | """ 98 | 99 | def __str__(self): 100 | """Printing a ContentFilter object yields the following output: 101 | 102 | Source file: 103 | Total characters: 104 | Alphabetic characters: 105 | Numerical characters: 106 | Whitespace characters: 107 | Number of lines: 108 | """ 109 | -------------------------------------------------------------------------------- /code/Exceptions_FileIO/hello_world.txt: -------------------------------------------------------------------------------- 1 | Hello, 2 | World! 3 | -------------------------------------------------------------------------------- /code/Matplotlib1/FARS.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/code/Matplotlib1/FARS.npy -------------------------------------------------------------------------------- /code/Matplotlib1/matplotlib_intro.py: -------------------------------------------------------------------------------- 1 | # matplotlib_intro.py 2 | """Python Essentials: Intro to Matplotlib. 3 | 4 | 5 | 6 | """ 7 | 8 | 9 | # Problem 1 10 | def var_of_means(n): 11 | """Create an (n x n) array of values randomly sampled from the standard 12 | normal distribution. Compute the mean of each row of the array. Return the 13 | variance of these means. 14 | 15 | Parameters: 16 | n (int): The number of rows and columns in the matrix. 17 | 18 | Returns: 19 | (float) The variance of the means of each row. 20 | """ 21 | raise NotImplementedError("Problem 1 Incomplete") 22 | 23 | 24 | def prob1(): 25 | """Create an array of the results of var_of_means() with inputs 26 | n = 100, 200, ..., 1000. Plot and show the resulting array. 27 | """ 28 | raise NotImplementedError("Problem 1 Incomplete") 29 | 30 | 31 | # Problem 2 32 | def prob2(): 33 | """Plot the functions sin(x), cos(x), and arctan(x) on the domain 34 | [-2pi, 2pi]. Make sure the domain is refined enough to produce a figure 35 | with good resolution. 36 | """ 37 | raise NotImplementedError("Problem 2 Incomplete") 38 | 39 | 40 | # Problem 3 41 | def prob3(): 42 | """Plot the curve f(x) = 1/(x-1) on the domain [-2,6]. 43 | 1. Split the domain so that the curve looks discontinuous. 44 | 2. Plot both curves with a thick, dashed magenta line. 45 | 3. Set the range of the x-axis to [-2,6] and the range of the 46 | y-axis to [-6,6]. 47 | """ 48 | raise NotImplementedError("Problem 3 Incomplete") 49 | 50 | 51 | # Problem 4 52 | def prob4(): 53 | """Plot the functions sin(x), sin(2x), 2sin(x), and 2sin(2x) on the 54 | domain [0, 2pi], each in a separate subplot of a single figure. 55 | 1. Arrange the plots in a 2 x 2 grid of subplots. 56 | 2. Set the limits of each subplot to [0, 2pi]x[-2, 2]. 57 | 3. Give each subplot an appropriate title. 58 | 4. Give the overall figure a title. 59 | 5. Use the following line colors and styles. 60 | sin(x): green solid line. 61 | sin(2x): red dashed line. 62 | 2sin(x): blue dashed line. 63 | 2sin(2x): magenta dotted line. 64 | """ 65 | raise NotImplementedError("Problem 4 Incomplete") 66 | 67 | 68 | # Problem 5 69 | def prob5(): 70 | """Visualize the data in FARS.npy. Use np.load() to load the data, then 71 | create a single figure with two subplots: 72 | 1. A scatter plot of longitudes against latitudes. Because of the 73 | large number of data points, use black pixel markers (use "k," 74 | as the third argument to plt.plot()). Label both axes. 75 | 2. A histogram of the hours of the day, with one bin per hour. 76 | Label and set the limits of the x-axis. 77 | """ 78 | raise NotImplementedError("Problem 5 Incomplete") 79 | 80 | 81 | # Problem 6 82 | def prob6(): 83 | """Plot the function g(x,y) = sin(x)sin(y)/xy on the domain 84 | [-2pi, 2pi]x[-2pi, 2pi]. 85 | 1. Create 2 subplots: one with a heat map of g, and one with a contour 86 | map of g. Choose an appropriate number of level curves, or specify 87 | the curves yourself. 88 | 2. Set the limits of each subplot to [-2pi, 2pi]x[-2pi, 2pi]. 89 | 3. Choose a non-default color scheme. 90 | 4. Include a color scale bar for each subplot. 91 | """ 92 | raise NotImplementedError("Problem 6 Incomplete") 93 | -------------------------------------------------------------------------------- /code/Matplotlib2/matplotlib2.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "colab_type": "text", 7 | "id": "-2R2EklVnwxF" 8 | }, 9 | "source": [ 10 | "# Pandas 2\n", 11 | "\n", 12 | "## Name\n", 13 | "\n", 14 | "## Class\n", 15 | "\n", 16 | "## Date" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "metadata": { 23 | "colab": {}, 24 | "colab_type": "code", 25 | "id": "B4EqVNKaPFma" 26 | }, 27 | "outputs": [], 28 | "source": [ 29 | "import numpy as np\n", 30 | "import pandas as pd\n", 31 | "import matplotlib.pyplot as plt" 32 | ] 33 | }, 34 | { 35 | "cell_type": "markdown", 36 | "metadata": {}, 37 | "source": [ 38 | "# Problem 1" 39 | ] 40 | }, 41 | { 42 | "cell_type": "code", 43 | "execution_count": null, 44 | "metadata": { 45 | "colab": {}, 46 | "colab_type": "code", 47 | "id": "nmDeeo7kP9L8" 48 | }, 49 | "outputs": [], 50 | "source": [ 51 | "def prob1():\n", 52 | " \"\"\"\n", 53 | " Create 3 visualizations of the crime data set.\n", 54 | " One of the visualizations should be a histogram.\n", 55 | " The visualizations should be clearly labelled and easy to understand.\n", 56 | " \"\"\"\n", 57 | " raise NotImplementedError(\"Problem 1 Incomplete\")" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": null, 63 | "metadata": {}, 64 | "outputs": [], 65 | "source": [ 66 | "prob1()" 67 | ] 68 | }, 69 | { 70 | "cell_type": "markdown", 71 | "metadata": { 72 | "colab_type": "text", 73 | "id": "uyGF9cEjsyFi" 74 | }, 75 | "source": [ 76 | "# Problem 2" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": null, 82 | "metadata": { 83 | "colab": {}, 84 | "colab_type": "code", 85 | "id": "DJD2o3UxQbYQ" 86 | }, 87 | "outputs": [], 88 | "source": [ 89 | " def prob2():\n", 90 | " \"\"\"\n", 91 | " Use crime_data.csv to plot the trends between Larceny and\n", 92 | " 1. Violent\n", 93 | " 2. Burglary\n", 94 | " 3. Aggravated Assault\n", 95 | " Each graph should be clearly labelled and readable.\n", 96 | " One of these variables does not have a linear trend with Larceny.\n", 97 | " Return a string identifying this variable.\n", 98 | " \"\"\"\n", 99 | " raise NotImplementedError(\"Problem 2 Incomplete\")" 100 | ] 101 | }, 102 | { 103 | "cell_type": "code", 104 | "execution_count": null, 105 | "metadata": {}, 106 | "outputs": [], 107 | "source": [ 108 | "prob2()" 109 | ] 110 | }, 111 | { 112 | "cell_type": "markdown", 113 | "metadata": { 114 | "colab_type": "text", 115 | "id": "UUuNrP5UszZ6" 116 | }, 117 | "source": [ 118 | "# Problem 3" 119 | ] 120 | }, 121 | { 122 | "cell_type": "code", 123 | "execution_count": null, 124 | "metadata": { 125 | "colab": {}, 126 | "colab_type": "code", 127 | "id": "lWPH4Ay2Ux3f" 128 | }, 129 | "outputs": [], 130 | "source": [ 131 | "def prob3():\n", 132 | " \"\"\"\n", 133 | " Use crime_data.csv to display the following distributions.\n", 134 | " 1. The distributions of Burglary, Violent, and Vehicle Theft \n", 135 | " as box plots\n", 136 | " 2. The distributions of Vehicle Thefts against Robberies as\n", 137 | " a hexbin plot.\n", 138 | " All plots should be labelled and easy to read.\n", 139 | " \"\"\"\n", 140 | " raise NotImplementedError(\"Problem 3 Incomplete\")" 141 | ] 142 | }, 143 | { 144 | "cell_type": "code", 145 | "execution_count": null, 146 | "metadata": {}, 147 | "outputs": [], 148 | "source": [ 149 | "prob3()" 150 | ] 151 | }, 152 | { 153 | "cell_type": "markdown", 154 | "metadata": { 155 | "colab_type": "text", 156 | "id": "mhJbAS1ts0q5" 157 | }, 158 | "source": [ 159 | "# Problem 4" 160 | ] 161 | }, 162 | { 163 | "cell_type": "code", 164 | "execution_count": null, 165 | "metadata": { 166 | "colab": {}, 167 | "colab_type": "code", 168 | "id": "OVF_p0fyZkXy" 169 | }, 170 | "outputs": [], 171 | "source": [ 172 | "def prob4():\n", 173 | " \"\"\"\n", 174 | " Create 3 plots that compare variables or universities.\n", 175 | " These plots should answer questions about the data, \n", 176 | " (e.g. What is the distribution of graduation rates? Do schools \n", 177 | " with lower student to faculty ratios have higher tuition costs? \n", 178 | " etc.). These plots should be easy to understand and have clear \n", 179 | " titles, variable names, and citations.\n", 180 | " \"\"\"\n", 181 | " raise NotImplementedError(\"Problem 4 Incomplete\")" 182 | ] 183 | }, 184 | { 185 | "cell_type": "code", 186 | "execution_count": null, 187 | "metadata": {}, 188 | "outputs": [], 189 | "source": [ 190 | "prob4()" 191 | ] 192 | } 193 | ], 194 | "metadata": { 195 | "colab": { 196 | "name": "pandas2.ipynb", 197 | "provenance": [], 198 | "version": "0.3.2" 199 | }, 200 | "kernelspec": { 201 | "display_name": "Python 3 (ipykernel)", 202 | "language": "python", 203 | "name": "python3" 204 | }, 205 | "language_info": { 206 | "codemirror_mode": { 207 | "name": "ipython", 208 | "version": 3 209 | }, 210 | "file_extension": ".py", 211 | "mimetype": "text/x-python", 212 | "name": "python", 213 | "nbconvert_exporter": "python", 214 | "pygments_lexer": "ipython3", 215 | "version": "3.7.4" 216 | } 217 | }, 218 | "nbformat": 4, 219 | "nbformat_minor": 1 220 | } 221 | -------------------------------------------------------------------------------- /code/Matplotlib3/animation.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": { 7 | "collapsed": true 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "import numpy as np\n", 12 | "import matplotlib.pyplot as plt\n", 13 | "import matplotlib.animation as animation\n", 14 | "from IPython.display import HTML" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": null, 20 | "metadata": {}, 21 | "outputs": [], 22 | "source": [ 23 | "%matplotlib notebook" 24 | ] 25 | }, 26 | { 27 | "cell_type": "markdown", 28 | "metadata": {}, 29 | "source": [ 30 | "## Problem 1\n", 31 | "\n", 32 | "Use the FuncAnimation class to animate the function $y = \\sin(x + 3t)$ where $x \\in [0, 2\\pi]$, and t ranges from 0 to 10 seconds.\n", 33 | "Save your animation to a file and embed the created file." 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": null, 39 | "metadata": { 40 | "collapsed": true 41 | }, 42 | "outputs": [], 43 | "source": [] 44 | }, 45 | { 46 | "cell_type": "markdown", 47 | "metadata": {}, 48 | "source": [ 49 | "## Problem 2\n", 50 | "\n", 51 | "The orbits for Mercury, Venus, Earth, and Mars are stored in the file `orbits.npz`. The file contains four NumPy arrays: `mercury`, `venus`, `earth`, and `mars`. The first column of each array contains the x-coordinates, the second column contains the y-coordinates, and the third column contians the z-coordinates, all relative to the Sun, and expressed in AU (astronomical units, the average distance between Earth and the Sun, approximately 150 million\n", 52 | "kilometers).\n", 53 | "\n", 54 | "Use `np.load('orbits.npz')` to load the data for the four planets' orbits. Create a 3D plot of the orbits, and compare your results with Figure 1.1." 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "execution_count": null, 60 | "metadata": { 61 | "collapsed": true 62 | }, 63 | "outputs": [], 64 | "source": [] 65 | }, 66 | { 67 | "cell_type": "markdown", 68 | "metadata": {}, 69 | "source": [ 70 | "## Problem 3\n", 71 | "\n", 72 | "Each row of the arrays in `orbits.npz` gives the position of the planets at a\n", 73 | "particular time. The arrays have 1400 points in time over a 700 day period (beginning on 2018-5-30). Create a 3D animation of the planet orbits. Display lines for the trajectories of the orbits and points for the current positions of the planets at each point in time. Your update() function will need to return a list of `Line3D` objects, one for each orbit trajectory and one for each planet position marker. Using `animation.save()`, save your animated plot, and embed you animated plot." 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": null, 79 | "metadata": { 80 | "collapsed": true 81 | }, 82 | "outputs": [], 83 | "source": [] 84 | }, 85 | { 86 | "cell_type": "markdown", 87 | "metadata": {}, 88 | "source": [ 89 | "## Problem 4\n", 90 | "\n", 91 | "Make a surface plot of the bivariate normal density function given by:\n", 92 | "\n", 93 | "$$f(\\mathbf{x}) = \\frac{1}{\\sqrt{\\det(2\\pi\\Sigma)}}\\exp[-\\frac{1}{2}(\\mathbf{x}-\\mathbf{\\mu})^{T}\\Sigma^{-1}(\\mathbf{x}-\\mathbf{\\mu})]$$\n", 94 | "\n", 95 | "Where $\\mathbf{x} = [x,y]^T \\in \\mathbb{R}^2$, $\\mathbf{\\mu} = [0,0]^T$ is the mean vector, and: $$\\Sigma = \\begin{bmatrix} 1 & 3/5 \\\\ 3/5 & 2 \\end{bmatrix}$$ is the covariance matrix." 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": null, 101 | "metadata": { 102 | "collapsed": true 103 | }, 104 | "outputs": [], 105 | "source": [] 106 | }, 107 | { 108 | "cell_type": "markdown", 109 | "metadata": {}, 110 | "source": [ 111 | "## Problem 5\n", 112 | "\n", 113 | "Use the data in vibration.npz to produce a surface animation of the solution\n", 114 | "to the wave equation for an elastic rectangular membrane. The file contains three NumPy arrays: `X`, `Y`, `Z`. `X` and `Y` are meshgrids of shape `(300,200)` corresponding to 300 points in\n", 115 | "the y-direction and 200 points in the x-direction, all corresponding to a 2x3 rectangle with one corner at the origin. `Z` is of shape `(150,300,200)`, giving the height of the vibrating membrane at each (x,y) point for 150 values of time. In the language of partial differential equations, this is the solution to the following intital/boundary value problem for the wave equation:\n", 116 | "\n", 117 | "$$u_{tt} = 6^2(u_{xx}+u_{yy})$$\n", 118 | "$$(x,y) \\in [0,2]\\times[0,3],t \\in [0,5]$$\n", 119 | "$$u(t,0,y)=u(t,2,y)=u(t,x,0)=u(t,x,3) = 0$$\n", 120 | "$$u(0,x,y) = xy(2-x)(3-y)$$\n", 121 | "\n", 122 | "Load the data with `np.load('vibration.npz')`. Create a 3D surface animation of the vibrating membrane. Save the animation and embed it in the notebook." 123 | ] 124 | }, 125 | { 126 | "cell_type": "code", 127 | "execution_count": null, 128 | "metadata": { 129 | "collapsed": true 130 | }, 131 | "outputs": [], 132 | "source": [] 133 | } 134 | ], 135 | "metadata": { 136 | "kernelspec": { 137 | "display_name": "Python 3 (ipykernel)", 138 | "language": "python", 139 | "name": "python3" 140 | }, 141 | "language_info": { 142 | "codemirror_mode": { 143 | "name": "ipython", 144 | "version": 3 145 | }, 146 | "file_extension": ".py", 147 | "mimetype": "text/x-python", 148 | "name": "python", 149 | "nbconvert_exporter": "python", 150 | "pygments_lexer": "ipython3", 151 | "version": "3.9.12" 152 | } 153 | }, 154 | "nbformat": 4, 155 | "nbformat_minor": 2 156 | } 157 | -------------------------------------------------------------------------------- /code/NumPyIntro/grid.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/code/NumPyIntro/grid.npy -------------------------------------------------------------------------------- /code/NumPyIntro/numpy_intro.py: -------------------------------------------------------------------------------- 1 | # numpy_intro.py 2 | """Python Essentials: Intro to NumPy. 3 | 4 | 5 | 6 | """ 7 | 8 | 9 | def prob1(): 10 | """Define the matrices A and B as arrays. Return the matrix product AB.""" 11 | raise NotImplementedError("Problem 1 Incomplete") 12 | 13 | 14 | def prob2(): 15 | """Define the matrix A as an array. Return the matrix -A^3 + 9A^2 - 15A.""" 16 | raise NotImplementedError("Problem 2 Incomplete") 17 | 18 | 19 | def prob3(): 20 | """Define the matrices A and B as arrays using the functions presented in 21 | this section of the manual (not np.array()). Calculate the matrix product ABA, 22 | change its data type to np.int64, and return it. 23 | """ 24 | raise NotImplementedError("Problem 3 Incomplete") 25 | 26 | 27 | def prob4(A): 28 | """Make a copy of 'A' and use fancy indexing to set all negative entries of 29 | the copy to 0. Return the resulting array. 30 | 31 | Example: 32 | >>> A = np.array([-3,-1,3]) 33 | >>> prob4(A) 34 | array([0, 0, 3]) 35 | """ 36 | raise NotImplementedError("Problem 4 Incomplete") 37 | 38 | 39 | def prob5(): 40 | """Define the matrices A, B, and C as arrays. Use NumPy's stacking functions 41 | to create and return the block matrix: 42 | | 0 A^T I | 43 | | A 0 0 | 44 | | B 0 C | 45 | where I is the 3x3 identity matrix and each 0 is a matrix of all zeros 46 | of the appropriate size. 47 | """ 48 | raise NotImplementedError("Problem 5 Incomplete") 49 | 50 | 51 | def prob6(A): 52 | """Divide each row of 'A' by the row sum and return the resulting array. 53 | Use array broadcasting and the axis argument instead of a loop. 54 | 55 | Example: 56 | >>> A = np.array([[1,1,0],[0,1,0],[1,1,1]]) 57 | >>> prob6(A) 58 | array([[ 0.5 , 0.5 , 0. ], 59 | [ 0. , 1. , 0. ], 60 | [ 0.33333333, 0.33333333, 0.33333333]]) 61 | """ 62 | raise NotImplementedError("Problem 6 Incomplete") 63 | 64 | 65 | def prob7(): 66 | """Given the array stored in grid.npy, return the greatest product of four 67 | adjacent numbers in the same direction (up, down, left, right, or 68 | diagonally) in the grid. Use slicing, as specified in the manual. 69 | """ 70 | raise NotImplementedError("Problem 7 Incomplete") 71 | -------------------------------------------------------------------------------- /code/ObjectOriented/object_oriented.py: -------------------------------------------------------------------------------- 1 | # object_oriented.py 2 | """Python Essentials: Object Oriented Programming. 3 | 4 | 5 | 6 | """ 7 | 8 | 9 | class Backpack: 10 | """A Backpack object class. Has a name and a list of contents. 11 | 12 | Attributes: 13 | name (str): the name of the backpack's owner. 14 | contents (list): the contents of the backpack. 15 | """ 16 | 17 | # Problem 1: Modify __init__() and put(), and write dump(). 18 | def __init__(self, name): 19 | """Set the name and initialize an empty list of contents. 20 | 21 | Parameters: 22 | name (str): the name of the backpack's owner. 23 | """ 24 | self.name = name 25 | self.contents = [] 26 | 27 | def put(self, item): 28 | """Add an item to the backpack's list of contents.""" 29 | self.contents.append(item) 30 | 31 | def take(self, item): 32 | """Remove an item from the backpack's list of contents.""" 33 | self.contents.remove(item) 34 | 35 | # Magic Methods ----------------------------------------------------------- 36 | 37 | # Problem 3: Write __eq__() and __str__(). 38 | def __add__(self, other): 39 | """Add the number of contents of each Backpack.""" 40 | return len(self.contents) + len(other.contents) 41 | 42 | def __lt__(self, other): 43 | """Compare two backpacks. If 'self' has fewer contents 44 | than 'other', return True. Otherwise, return False. 45 | """ 46 | return len(self.contents) < len(other.contents) 47 | 48 | 49 | # An example of inheritance. You are not required to modify this class. 50 | class Knapsack(Backpack): 51 | """A Knapsack object class. Inherits from the Backpack class. 52 | A knapsack is smaller than a backpack and can be tied closed. 53 | 54 | Attributes: 55 | name (str): the name of the knapsack's owner. 56 | color (str): the color of the knapsack. 57 | max_size (int): the maximum number of items that can fit inside. 58 | contents (list): the contents of the backpack. 59 | closed (bool): whether or not the knapsack is tied shut. 60 | """ 61 | 62 | def __init__(self, name, color): 63 | """Use the Backpack constructor to initialize the name, color, 64 | and max_size attributes. A knapsack only holds 3 item by default. 65 | 66 | Parameters: 67 | name (str): the name of the knapsack's owner. 68 | color (str): the color of the knapsack. 69 | max_size (int): the maximum number of items that can fit inside. 70 | """ 71 | Backpack.__init__(self, name, color, max_size=3) 72 | self.closed = True 73 | 74 | def put(self, item): 75 | """If the knapsack is untied, use the Backpack.put() method.""" 76 | if self.closed: 77 | print("I'm closed!") 78 | else: 79 | Backpack.put(self, item) 80 | 81 | def take(self, item): 82 | """If the knapsack is untied, use the Backpack.take() method.""" 83 | if self.closed: 84 | print("I'm closed!") 85 | else: 86 | Backpack.take(self, item) 87 | 88 | def weight(self): 89 | """Calculate the weight of the knapsack by counting the length of the 90 | string representations of each item in the contents list. 91 | """ 92 | return sum(len(str(item)) for item in self.contents) 93 | 94 | 95 | # Problem 2: Write a 'Jetpack' class that inherits from the 'Backpack' class. 96 | 97 | 98 | # Problem 4: Write a 'ComplexNumber' class. 99 | -------------------------------------------------------------------------------- /code/Pandas1/pandas1.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "colab_type": "text", 7 | "id": "hr6QvWC1sVno" 8 | }, 9 | "source": [ 10 | "# Pandas 1\n", 11 | "\n", 12 | "## Name\n", 13 | "\n", 14 | "## Class\n", 15 | "\n", 16 | "## Date" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "metadata": { 23 | "colab": {}, 24 | "colab_type": "code", 25 | "id": "D1pxi6sWEcmJ" 26 | }, 27 | "outputs": [], 28 | "source": [ 29 | "import numpy as np\n", 30 | "import pandas as pd" 31 | ] 32 | }, 33 | { 34 | "cell_type": "markdown", 35 | "metadata": { 36 | "colab_type": "text", 37 | "id": "Y8nzrZCaE4bn" 38 | }, 39 | "source": [ 40 | "# Problem 1" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": null, 46 | "metadata": {}, 47 | "outputs": [], 48 | "source": [ 49 | "# Prob 1\n", 50 | "def prob1(file='budget.csv'):\n", 51 | " \"\"\"\"\n", 52 | " Read in budget.csv as a DataFrame with the index as column 0 and perform each of these operations on the DataFrame in order. \n", 53 | " \n", 54 | " 1) Reindex the columns such that amount spent on groceries is the first column and all other columns maintain the same ordering.\n", 55 | " 2) Sort the DataFrame in descending order based on how much money was spent on Groceries.\n", 56 | " 3) Reset all values in the 'Rent' column to 800.0.\n", 57 | " 4) Reset all values in the first 5 data points to 0.0\n", 58 | " \n", 59 | " Return the values of the updated DataFrame as a NumPy array.\n", 60 | " \n", 61 | " Parameters:\n", 62 | " file (str): name of datafile\n", 63 | " \n", 64 | " Return:\n", 65 | " values (ndarray): values of DataFrame\n", 66 | " \"\"\"\n", 67 | " raise NotImplementedError(\"Problem 1 Incomplete\")" 68 | ] 69 | }, 70 | { 71 | "cell_type": "markdown", 72 | "metadata": { 73 | "colab_type": "text", 74 | "id": "FcGE9Qq5scpv" 75 | }, 76 | "source": [ 77 | "# Problem 2" 78 | ] 79 | }, 80 | { 81 | "cell_type": "code", 82 | "execution_count": null, 83 | "metadata": { 84 | "colab": {}, 85 | "colab_type": "code", 86 | "id": "bZIdjL74RuuO" 87 | }, 88 | "outputs": [], 89 | "source": [ 90 | "# Prob 2\n", 91 | "def prob2(file='budget.csv'):\n", 92 | " \"\"\"\n", 93 | " Read in file as DataFrame.\n", 94 | " Fill all NaN values with 0.0.\n", 95 | " Create two new columns, 'Living Expenses' and 'Other'. \n", 96 | " Sum the columns 'Rent', 'Groceries', 'Gas' and 'Utilities' and set it as the value of 'Living Expenses'.\n", 97 | " Sum the columns 'Dining Out', 'Out With Friends' and 'Netflix' and set as the value of 'Other'.\n", 98 | " Identify which column, other than 'Living Expenses' correlates most with 'Living Expenses'\n", 99 | " and which column other than 'Other' correlates most with 'Other'.\n", 100 | "\n", 101 | " Return the names of each of those columns as a tuple.\n", 102 | " The first should be of the column corresponding to \\li{'Living Expenses'} and the second to \\li{'Other'}.\n", 103 | " \n", 104 | " Parameters:\n", 105 | " file (str): name of datafile\n", 106 | " \n", 107 | " Return:\n", 108 | " values (tuple): (name of column that most relates to Living Expenses, name of column that most relates to Other)\n", 109 | " \"\"\"\n", 110 | " raise NotImplementedError(\"Problem 2 Incomplete\")" 111 | ] 112 | }, 113 | { 114 | "cell_type": "markdown", 115 | "metadata": { 116 | "colab_type": "text", 117 | "id": "qVHAwFRRseXh" 118 | }, 119 | "source": [ 120 | "# Problem 3" 121 | ] 122 | }, 123 | { 124 | "cell_type": "code", 125 | "execution_count": null, 126 | "metadata": { 127 | "colab": {}, 128 | "colab_type": "code", 129 | "id": "35VAshdqZhVD" 130 | }, 131 | "outputs": [], 132 | "source": [ 133 | "def prob3(file='crime_data.csv'):\n", 134 | " \"\"\"\n", 135 | " Read in crime data and use pandas to answer the following questions.\n", 136 | " \n", 137 | " Set the index as the column 'Year', and return the answers to each question as a tuple.\n", 138 | " \n", 139 | " 1) Identify the three crimes that have a mean over 1,500,000. \n", 140 | " Of these three crimes, which two are very correlated? \n", 141 | " Which of these two crimes has a greater maximum value?\n", 142 | " Save the title of this column as a variable to return as the answer.\n", 143 | " \n", 144 | " 2) Examine the data since 2000.\n", 145 | " Sort this data (in ascending order) according to number of murders.\n", 146 | " Find the years where Aggravated Assault is greater than 850,000.\n", 147 | " Save the indices (the years) of the masked and reordered DataFrame as a NumPy array to return as the answer.\n", 148 | " \n", 149 | " 3) What year had the highest crime rate? \n", 150 | " In this year, which crime was committed the most? \n", 151 | " What percentage of the total crime that year was it? \n", 152 | " Save this value as a float.\n", 153 | " \n", 154 | " \n", 155 | " Parameters:\n", 156 | " file (str): data\n", 157 | " \n", 158 | " Return:\n", 159 | " ans_1 (string): answer to Question 1\n", 160 | " ans_2 (ndarray): answer to Question 2\n", 161 | " ans_3 (float): answer to Question 3\n", 162 | " \"\"\"\n", 163 | " raise NotImplementedError(\"Problem 3 Incomplete\")" 164 | ] 165 | }, 166 | { 167 | "cell_type": "markdown", 168 | "metadata": { 169 | "colab_type": "text", 170 | "id": "4pfN6PbxsgC3" 171 | }, 172 | "source": [ 173 | "# Problem 4" 174 | ] 175 | }, 176 | { 177 | "cell_type": "code", 178 | "execution_count": null, 179 | "metadata": { 180 | "colab": {}, 181 | "colab_type": "code", 182 | "id": "TAavKLA17LsN" 183 | }, 184 | "outputs": [], 185 | "source": [ 186 | "def prob4(file='DJIA.csv'):\n", 187 | " \"\"\"\n", 188 | "\n", 189 | " Read the data with a DatetimeIndex as the index.\n", 190 | " Drop rows any rows without numerical values, cast the \"VALUE\" column to floats, then return the updated DataFrame.\n", 191 | "\n", 192 | " Parameters:\n", 193 | " file (str): data file\n", 194 | " Returns:\n", 195 | " df (DataFrame): updated DataFrame of stock market data\n", 196 | " \"\"\"\n", 197 | " raise NotImplementedError(\"Problem 4 Incomplete\")" 198 | ] 199 | }, 200 | { 201 | "cell_type": "markdown", 202 | "metadata": { 203 | "colab_type": "text", 204 | "id": "I663KesNsjMK" 205 | }, 206 | "source": [ 207 | "# Problem 5" 208 | ] 209 | }, 210 | { 211 | "cell_type": "code", 212 | "execution_count": null, 213 | "metadata": {}, 214 | "outputs": [], 215 | "source": [ 216 | "def prob5(file='paychecks.csv'):\n", 217 | " \"\"\"\n", 218 | "\n", 219 | " Create data_range for index of paycheck data.\n", 220 | "\n", 221 | " Parameters:\n", 222 | " file (str): data file\n", 223 | " Returns:\n", 224 | " df (DataFrame): DataFrame of paycheck data\n", 225 | " \"\"\"\n", 226 | " raise NotImplementedError(\"Problem 5 Incomplete\")" 227 | ] 228 | }, 229 | { 230 | "cell_type": "markdown", 231 | "metadata": { 232 | "colab_type": "text", 233 | "id": "I663KesNsjMK" 234 | }, 235 | "source": [ 236 | "# Problem 6" 237 | ] 238 | }, 239 | { 240 | "cell_type": "code", 241 | "execution_count": null, 242 | "metadata": { 243 | "colab": {}, 244 | "colab_type": "code", 245 | "id": "KGxh0mpSDLDD" 246 | }, 247 | "outputs": [], 248 | "source": [ 249 | "def prob6(file='DJIA.csv'):\n", 250 | " \"\"\"\n", 251 | " Compute the following information about the DJIA dataset\n", 252 | " 1. The single day with the largest gain\n", 253 | " 2. The single day with the largest loss\n", 254 | "\n", 255 | " Parameters:\n", 256 | " file (str): data file\n", 257 | " Returns:\n", 258 | " max_day ( 4 | 5 | 6 | """ 7 | 8 | 9 | # Problem 1 (write code below) 10 | 11 | 12 | # Problem 2 13 | def sphere_volume(r): 14 | """Return the volume of the sphere of radius 'r'. 15 | Use 3.14159 for pi in your computation. 16 | """ 17 | raise NotImplementedError("Problem 2 Incomplete") 18 | 19 | 20 | # Problem 3 21 | def isolate(a, b, c, d, e): 22 | """Print the arguments separated by spaces, but print 5 spaces on either 23 | side of b. 24 | """ 25 | raise NotImplementedError("Problem 3 Incomplete") 26 | 27 | 28 | # Problem 4 29 | def first_half(my_string): 30 | """Return the first half of the string 'my_string'. Exclude the 31 | middle character if there are an odd number of characters. 32 | 33 | Examples: 34 | >>> first_half("python") 35 | 'pyt' 36 | >>> first_half("ipython") 37 | 'ipy' 38 | """ 39 | raise NotImplementedError("Problem 4 Incomplete") 40 | 41 | 42 | def backward(my_string): 43 | """Return the reverse of the string 'my_string'. 44 | 45 | Examples: 46 | >>> backward("python") 47 | 'nohtyp' 48 | >>> backward("ipython") 49 | 'nohtypi' 50 | """ 51 | raise NotImplementedError("Problem 4 Incomplete") 52 | 53 | 54 | # Problem 5 55 | def list_ops(): 56 | """Define a list with the entries "bear", "ant", "cat", and "dog". 57 | Perform the following operations on the list: 58 | - Append "eagle". 59 | - Replace the entry at index 2 with "fox". 60 | - Remove (or pop) the entry at index 1. 61 | - Sort the list in reverse alphabetical order. 62 | - Replace "eagle" with "hawk". 63 | - Add the string "hunter" to the last entry in the list. 64 | Return the resulting list. 65 | 66 | Examples: 67 | >>> list_ops() 68 | ['fox', 'hawk', 'dog', 'bearhunter'] 69 | """ 70 | raise NotImplementedError("Problem 5 Incomplete") 71 | 72 | 73 | # Problem 6 74 | def pig_latin(word): 75 | """Translate the string 'word' into Pig Latin, and return the new word. 76 | 77 | Examples: 78 | >>> pig_latin("apple") 79 | 'applehay' 80 | >>> pig_latin("banana") 81 | 'ananabay' 82 | """ 83 | raise NotImplementedError("Problem 6 Incomplete") 84 | 85 | 86 | # Problem 7 87 | def palindrome(): 88 | """Find and retun the largest panindromic number made from the product 89 | of two 3-digit numbers. 90 | """ 91 | raise NotImplementedError("Problem 7 Incomplete") 92 | 93 | 94 | # Problem 8 95 | def alt_harmonic(n): 96 | """Return the partial sum of the first n terms of the alternating 97 | harmonic series, which approximates ln(2). 98 | """ 99 | raise NotImplementedError("Problem 8 Incomplete") 100 | -------------------------------------------------------------------------------- /code/StandardLibrary/box.py: -------------------------------------------------------------------------------- 1 | # box.py 2 | """Python Essentials: The Standard Library. Auxiliary file (do not modify).""" 3 | 4 | from itertools import combinations 5 | 6 | 7 | def isvalid(roll, remaining): 8 | """Check to see whether or not a roll is valid. That is, check if there 9 | exists a combination of the entries of 'remaining' that sum up to 'roll'. 10 | 11 | Parameters: 12 | roll (int): The value of a dice roll, between 1 and 12 (inclusive). 13 | This can either be a roll of one die or a roll of two dice 14 | depending on the remaining values. 15 | remaining (list): The list of the numbers that still need to be 16 | removed before the box can be shut. 17 | 18 | Returns: 19 | True if the roll is valid. 20 | False if the roll is invalid. 21 | """ 22 | if roll not in range(1, 13): 23 | return False 24 | for i in range(1, len(remaining) + 1): 25 | if any([sum(combo) == roll for combo in combinations(remaining, i)]): 26 | return True 27 | return False 28 | 29 | 30 | def parse_input(player_input, remaining): 31 | """Convert a string of numbers into a list of unique integers, if possible. 32 | Then check that each of those integers is an entry in the other list. 33 | 34 | Parameters: 35 | player_input (str): A string of integers, separated by spaces. 36 | The player's choices for which numbers to remove. 37 | remaining (list): The list of the numbers that still need to be 38 | removed before the box can be shut. 39 | 40 | Returns: 41 | A list of the integers if the input was valid. 42 | An empty list if the input was invalid. 43 | """ 44 | try: 45 | choices = [int(i) for i in player_input.split()] 46 | if len(set(choices)) != len(choices): 47 | raise ValueError 48 | if any([number not in remaining for number in choices]): 49 | raise ValueError 50 | return choices 51 | except ValueError: 52 | return [] 53 | -------------------------------------------------------------------------------- /code/StandardLibrary/standard_library.py: -------------------------------------------------------------------------------- 1 | # standard_library.py 2 | """Python Essentials: The Standard Library. 3 | 4 | 5 | 6 | """ 7 | 8 | 9 | # Problem 1 10 | def prob1(L): 11 | """Return the minimum, maximum, and average of the entries of L 12 | (in that order, separated by a comma). 13 | """ 14 | raise NotImplementedError("Problem 1 Incomplete") 15 | 16 | 17 | # Problem 2 18 | def prob2(): 19 | """Determine which Python objects are mutable and which are immutable. 20 | Test integers, strings, lists, tuples, and sets. Print your results. 21 | """ 22 | raise NotImplementedError("Problem 2 Incomplete") 23 | 24 | 25 | # Problem 3 26 | def hypot(a, b): 27 | """Calculate and return the length of the hypotenuse of a right triangle. 28 | Do not use any functions other than sum(), product() and sqrt() that are 29 | imported from your 'calculator' module. 30 | 31 | Parameters: 32 | a: the length one of the sides of the triangle. 33 | b: the length the other non-hypotenuse side of the triangle. 34 | Returns: 35 | The length of the triangle's hypotenuse. 36 | """ 37 | raise NotImplementedError("Problem 3 Incomplete") 38 | 39 | 40 | # Problem 4 41 | def power_set(A): 42 | """Use itertools to compute the power set of A. 43 | 44 | Parameters: 45 | A (iterable): a str, list, set, tuple, or other iterable collection. 46 | 47 | Returns: 48 | (list(sets)): The power set of A as a list of sets. 49 | """ 50 | raise NotImplementedError("Problem 4 Incomplete") 51 | 52 | 53 | # Problem 5: Implement shut the box. 54 | def shut_the_box(player, timelimit): 55 | """Play a single game of shut the box.""" 56 | raise NotImplementedError("Problem 5 Incomplete") 57 | -------------------------------------------------------------------------------- /code/StrEstPaper/LaTeXtemplates/LaTeX_projtemplate.bib: -------------------------------------------------------------------------------- 1 | @ARTICLE{Aiyagari:1994, 2 | AUTHOR = {S. Rao Aiyagari}, 3 | TITLE = {Uninsured Idiosyncratic Risk and Aggregate Saving}, 4 | JOURNAL = {Quarterly Journal of Economics}, 5 | YEAR = {1994}, 6 | volume = {109}, 7 | number = {3}, 8 | pages = {659-684}, 9 | month = {August}, 10 | } 11 | 12 | @ARTICLE{Auerbach:1996, 13 | AUTHOR = {Alan J. Auerbach}, 14 | TITLE = {Dynamic Revenue Estimation}, 15 | JOURNAL = {Journal of Economic Perspectives}, 16 | YEAR = {1996}, 17 | volume = {10}, 18 | number = {1}, 19 | month = {Winter}, 20 | } 21 | 22 | @ARTICLE{Auerbach:2005, 23 | AUTHOR = {Alan J. Auerbach}, 24 | TITLE = {Dynamic Scoring: An Introduction to the Issues}, 25 | JOURNAL = {American Economic Review}, 26 | YEAR = {2005}, 27 | volume = {95}, 28 | number = {2}, 29 | month = {May}, 30 | pages = {421-425}, 31 | } 32 | 33 | @BOOK{AuerbachKotlikoff:1987, 34 | Author = {Alan J. Auerbach and Lawrence J. Kotlikoff}, 35 | Publisher = {Cambridge University Press}, 36 | Title = {Dynamic Fiscal Policy}, 37 | Year = {1987}, 38 | } 39 | 40 | @TECHREPORT{BrillViard:2011, 41 | AUTHOR = {Alex M. Brill and Alan D. Viard}, 42 | TITLE = {The Benefits and Limitations of Income Tax Reform}, 43 | INSTITUTION = {American Enterprise Institute for Public Policy Research}, 44 | YEAR = {2011}, 45 | type = {Tax Policy Outlook}, 46 | number = {2}, 47 | month = {September}, 48 | } 49 | 50 | @ARTICLE{CagettiDeNardi:2008, 51 | AUTHOR = {Marco Cagetti and Mariacristina {De Nardi}}, 52 | TITLE = {Wealth Inequality: Data and Models}, 53 | JOURNAL = {Macroeconomic Dynamics}, 54 | YEAR = {2008}, 55 | volume = {12}, 56 | number = {Supplement S2}, 57 | pages = {285-313}, 58 | month = {September}, 59 | } 60 | 61 | @techreport{DEPR2015, 62 | Author = {Jason DeBacker and Richard W. Evans and Kerk L. Phillips and Shanthi Ramnath}, 63 | Institution = {Mimeo}, 64 | Title = {Estimating the Hourly Earnings Processes of Top Earners}, 65 | Year = {2015}} 66 | 67 | @TECHREPORT{Census:2015, 68 | AUTHOR = {{Census Bureau}}, 69 | TITLE = {Annual Estimates of the Resident Population by Single Year of Age and Sex: April 1, 2010 to July 1, 2013 (both sexes)}, 70 | INSTITUTION = {U.S. Census Bureau}, 71 | YEAR = {2015}, 72 | type = {National Characteristics}, 73 | number = {Vintage 2013}, 74 | address = {http://www.census.gov/popest/data/national/asrh/2013/index.html}, 75 | } 76 | 77 | @TECHREPORT{DeNardi:2015, 78 | AUTHOR = {Mariacristina {De Nardi}}, 79 | INSTITUTION = {National Bureau of Economic Research}, 80 | MONTH = {April}, 81 | NUMBER = {No. 21106}, 82 | TITLE = {Quantitative Models of Wealth Inequality: A Survey}, 83 | type = {NBER Working Paper}, 84 | YEAR = {2015}, 85 | } 86 | -------------------------------------------------------------------------------- /code/StrEstPaper/LaTeXtemplates/LaTeX_projtemplate.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/code/StrEstPaper/LaTeXtemplates/LaTeX_projtemplate.pdf -------------------------------------------------------------------------------- /code/StrEstPaper/LaTeXtemplates/LaTeX_projtemplate.tex: -------------------------------------------------------------------------------- 1 | \documentclass[letterpaper,12pt]{article} 2 | 3 | \usepackage{threeparttable} 4 | \usepackage{geometry} 5 | \geometry{letterpaper,tmargin=1in,bmargin=1in,lmargin=1.25in,rmargin=1.25in} 6 | \usepackage[format=hang,font=normalsize,labelfont=bf]{caption} 7 | \usepackage{amsmath} 8 | \usepackage{multirow} 9 | \usepackage{array} 10 | \usepackage{delarray} 11 | \usepackage{amssymb} 12 | \usepackage{amsthm} 13 | \usepackage{lscape} 14 | \usepackage{natbib} 15 | \usepackage{setspace} 16 | \usepackage{float,color} 17 | \usepackage[pdftex]{graphicx} 18 | \usepackage{pdfsync} 19 | \usepackage{verbatim} 20 | \usepackage{placeins} 21 | \usepackage{geometry} 22 | \usepackage{pdflscape} 23 | \synctex=1 24 | \usepackage{hyperref} 25 | \hypersetup{colorlinks,linkcolor=red,urlcolor=blue,citecolor=red} 26 | \usepackage{bm} 27 | 28 | 29 | \theoremstyle{definition} 30 | \newtheorem{theorem}{Theorem} 31 | \newtheorem{acknowledgement}[theorem]{Acknowledgement} 32 | \newtheorem{algorithm}[theorem]{Algorithm} 33 | \newtheorem{axiom}[theorem]{Axiom} 34 | \newtheorem{case}[theorem]{Case} 35 | \newtheorem{claim}[theorem]{Claim} 36 | \newtheorem{conclusion}[theorem]{Conclusion} 37 | \newtheorem{condition}[theorem]{Condition} 38 | \newtheorem{conjecture}[theorem]{Conjecture} 39 | \newtheorem{corollary}[theorem]{Corollary} 40 | \newtheorem{criterion}[theorem]{Criterion} 41 | \newtheorem{definition}{Definition} % Number definitions on their own 42 | \newtheorem{derivation}{Derivation} % Number derivations on their own 43 | \newtheorem{example}[theorem]{Example} 44 | \newtheorem{exercise}[theorem]{Exercise} 45 | \newtheorem{lemma}[theorem]{Lemma} 46 | \newtheorem{notation}[theorem]{Notation} 47 | \newtheorem{problem}[theorem]{Problem} 48 | \newtheorem{proposition}{Proposition} % Number propositions on their own 49 | \newtheorem{remark}[theorem]{Remark} 50 | \newtheorem{solution}[theorem]{Solution} 51 | \newtheorem{summary}[theorem]{Summary} 52 | \bibliographystyle{aer} 53 | \newcommand\ve{\varepsilon} 54 | \renewcommand\theenumi{\roman{enumi}} 55 | \newcommand\norm[1]{\left\lVert#1\right\rVert} 56 | 57 | \begin{document} 58 | 59 | \begin{titlepage} 60 | \title{Title of My Paper \thanks{You can put thanks here, affiliation here, anything you want here.} 61 | } 62 | \author{ 63 | Your Name\footnote{Your University, Your Department, Academic address, (???) ???-????, \href{mailto:your.emailr@uchicago.edu}{your.emailr@uchicago.edu}.} \\[-2pt] 64 | \and 65 | Other Name\footnote{Your University, Your Department, Academic address, (???) ???-????, \href{mailto:your.emailr@uchicago.edu}{your.emailr@uchicago.edu}.}} 66 | \date{March 2018 \\ 67 | \scriptsize{(version 18.03.a)}} 68 | \maketitle 69 | \vspace{-9mm} 70 | \begin{abstract} 71 | \small{Put abstract here. 72 | \vspace{3mm} 73 | 74 | \noindent\textit{keywords:}\: Static scoring, revenue estimates, dynamic scoring. 75 | 76 | \vspace{3mm} 77 | 78 | \noindent\textit{JEL classification:} D91, E21, H30 79 | } 80 | 81 | \end{abstract} 82 | \thispagestyle{empty} 83 | \end{titlepage} 84 | 85 | 86 | \begin{spacing}{1.5}{} 87 | 88 | \section{Introduction}\label{SecIntro} 89 | 90 | Put introduction here. You'll probably want some references here like \citet{Auerbach:1996} or \citet{DEPR2015}. These citations use the \texttt{natbib} package above and require a call to the \texttt{bibliography} command just before the appendix section. 91 | 92 | 93 | \section{Model}\label{SecModel} 94 | 95 | Put model description here. 96 | 97 | 98 | \section{Data}\label{SecData} 99 | 100 | Put data description here. 101 | 102 | 103 | \section{Estimation}\label{SecEstimation} 104 | 105 | Put estimation details here. You might want to use a table. Table \ref{TabTable1} is an example of a table generated by the code below. 106 | 107 | \begin{table}[htbp] \centering \captionsetup{width=5.8in} 108 | \caption{\label{TabTable1}\textbf{Percent change in macroeconomic variables over the budget window and in steady-state from policy change}} 109 | \begin{threeparttable} 110 | \begin{tabular}{>{\scriptsize}l |>{\scriptsize}r >{\scriptsize}r >{\scriptsize}r >{\scriptsize}r >{\scriptsize}r >{\scriptsize}r >{\scriptsize}r >{\scriptsize}r >{\scriptsize}r >{\scriptsize}r |>{\scriptsize}r >{\scriptsize}r} 111 | \hline\hline 112 | \multicolumn{1}{c}{\scriptsize{Macroeconomic}} & & & & & & & & & & & \multicolumn{1}{c}{\scriptsize{2016-}} & \\[-2mm] 113 | \multicolumn{1}{c}{\scriptsize{variables}} & 2016 & 2017 & 2018 & 2019 & 2020 & 2021 & 2022 & 2023 & 2024 & 2025 & \multicolumn{1}{c}{\scriptsize{2025}} & \multicolumn{1}{c}{\scriptsize{SS}} \\ 114 | \hline 115 | GDP & 0.54 & 0.50 & 0.55 & 0.91 & 0.90 & 1.02 & 1.03 & 1.02 & 1.03 & 1.22 & 0.87 & 1.40 \\ 116 | Consumption & 0.21 & 0.28 & 0.35 & 0.44 & 0.52 & 0.58 & 0.65 & 0.70 & 0.75 & 0.86 & 0.53 & 1.30 \\ 117 | Investment & 1.28 & 0.99 & 0.98 & 1.93 & 1.74 & 1.96 & 1.88 & 1.72 & 1.67 & 2.02 & 1.62 & 1.65 \\ 118 | Hours Worked & 0.83 & 0.71 & 0.73 & 1.25 & 1.16 & 1.27 & 1.23 & 1.15 & 1.13 & 1.37 & 1.08 & 1.27 \\ 119 | \hline 120 | Avg. Wage & -0.29 & -0.21 & -0.19 & -0.35 & -0.26 & -0.26 & -0.20 & -0.13 & -0.09 & -0.15 & -0.21 & 0.13 \\ 121 | Interest Rate & 1.00 & 0.72 & 0.66 & 1.20 & 0.90 & 0.91 & 0.70 & 0.47 & 0.33 & 0.56 & 0.75 & -0.51 \\ 122 | \hline 123 | Total Taxes & -3.59 & -2.42 & -3.10 & -8.23 & -8.21 & -8.36 & -8.32 & -8.53 & -8.89 & -8.27 & -6.71 & -7.43 \\ 124 | \hline\hline 125 | \end{tabular} 126 | % \begin{tablenotes} 127 | % \scriptsize{\item[]Note: Maybe put sources here.} 128 | % \end{tablenotes} 129 | \end{threeparttable} 130 | \end{table} 131 | 132 | 133 | \section{Experiment}\label{SecExperiment} 134 | 135 | Put experiment results here. You might want to include a figure. Here is a some figure code that generated Figure \ref{FigLogAbility}. Note that I put my images in an \texttt{images} folder in the directory of this \LaTeX file. 136 | 137 | \begin{figure}[htb]\centering \captionsetup{width=4.0in} 138 | \caption{\label{FigLogAbility}\textbf{Exogenous life cycle income ability paths $\log(e_{j,s})$ with $S=80$ and $J=7$}} 139 | \fbox{\resizebox{4.0in}{2.7in}{\includegraphics{./images/ability_log_2D.png}}} 140 | \end{figure} 141 | 142 | 143 | \section{Conclusion}\label{SecConclusion} 144 | 145 | Put conclusion here. 146 | 147 | \clearpage 148 | 149 | 150 | \end{spacing} 151 | 152 | 153 | \newpage 154 | \bibliography{LaTeX_projtemplate.bib} 155 | 156 | 157 | \newpage 158 | \renewcommand{\theequation}{A.\arabic{section}.\arabic{equation}} 159 | % redefine the command that creates the section number 160 | \renewcommand{\thesection}{A-\arabic{section}} % redefine the command that creates the equation number 161 | \setcounter{equation}{0} % reset counter 162 | \setcounter{section}{0} % reset section number 163 | \section*{APPENDIX} % use *-form to suppress numbering 164 | 165 | \begin{spacing}{1.0} 166 | 167 | \section{Some Appendix}\label{AppSomeAppendix} 168 | 169 | You can put appendices here at the end of the paper using section commands. 170 | 171 | 172 | 173 | 174 | \end{spacing} 175 | 176 | \end{document} 177 | -------------------------------------------------------------------------------- /code/StrEstPaper/LaTeXtemplates/LaTeX_slides.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/code/StrEstPaper/LaTeXtemplates/LaTeX_slides.pdf -------------------------------------------------------------------------------- /code/StrEstPaper/LaTeXtemplates/LaTeX_slides.tex: -------------------------------------------------------------------------------- 1 | \documentclass[11pt]{beamer} 2 | \usetheme{Darmstadt} 3 | \useoutertheme{split} 4 | \useoutertheme{miniframes} 5 | \usepackage{hyperref} 6 | \hypersetup{colorlinks, urlcolor=blue} 7 | \usepackage{bm} 8 | \usepackage{times} 9 | \usefonttheme{structurebold} 10 | \usepackage{array} 11 | \usepackage[english]{babel} 12 | \usepackage{amsmath,amssymb} 13 | \usepackage[latin1]{inputenc} 14 | 15 | %Code snippets and syntax highlighting 16 | \usepackage{listings} 17 | %Settings for Listings 18 | \lstset{ 19 | language=Python, 20 | basicstyle=\ttfamily, 21 | keywordstyle=\color{blue}\ttfamily, 22 | stringstyle=\color{red}\ttfamily, 23 | commentstyle=\color{green}\ttfamily, 24 | morecomment=[l][\color{magenta}]{\#} 25 | } 26 | 27 | \usepackage{array} 28 | \usepackage{threeparttable} 29 | \usepackage{colortbl} 30 | \usepackage{multirow} 31 | \usepackage{amsthm} 32 | \usepackage{float,graphicx,color} 33 | \newtheorem*{thm}{Theorem} 34 | \theoremstyle{definition} 35 | %\numberwithin{equation}{section} 36 | \newtheorem*{defn}{Definition} 37 | \newcommand\boldline{\arrayrulewidth{1pt}\hline} 38 | \newcommand\ve{\varepsilon} 39 | 40 | 41 | \setbeamercovered{dynamic} 42 | 43 | \title[Short version of title]{Full version of title} 44 | \author[FirstAuthor and SecondAuthor]{\textbf{First Author} \and \textbf{Second Author}} 45 | \date{February 2019} 46 | 47 | 48 | \begin{document} 49 | 50 | \frame{\titlepage} 51 | 52 | 53 | \section{Intro} % This puts a section heading at the top of the slides 54 | 55 | \frame{ 56 | \frametitle{Introduction} 57 | \begin{enumerate} 58 | \item<1-> This is a numbered list 59 | \item<2-> This second item in numbered list comes up on next click 60 | \vspace{5mm} 61 | \item<3-> The vspace command puts spaces between your items 62 | \end{enumerate} 63 | \begin{itemize} 64 | \item<4-> Bulleted lists are also good 65 | \item<4-> And you can set all the bullets to appear at once 66 | \end{itemize} 67 | \begin{block}<5->{Block (blue) and alertblock (red)} 68 | The block and alertblock environment makes these nice boxes that add emphasis 69 | \end{block} 70 | } 71 | 72 | 73 | \section{Images} 74 | 75 | \begin{frame} 76 | \frametitle{Here is an image} 77 | \begin{figure}[htb]\centering 78 | \fbox{\resizebox{3.5in}{2.7in}{\includegraphics{images/ability_log_2D.png}}} 79 | \end{figure} 80 | \end{frame} 81 | 82 | 83 | \section{Tables} 84 | 85 | \frame{ 86 | \frametitle{Here is a table} 87 | \begin{tabular}{>{\small}c >{\small}l >{\small}r} 88 | \hline\hline 89 | Variable & Description & Value \\ 90 | \hline 91 | $\beta$ & discount factor & 0.96 \\ 92 | $\alpha$ & capital share of income & 0.35 \\ 93 | \hline\hline 94 | \end{tabular} 95 | } 96 | 97 | 98 | \end{document} 99 | -------------------------------------------------------------------------------- /code/StrEstPaper/LaTeXtemplates/images/ability_log_2D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/code/StrEstPaper/LaTeXtemplates/images/ability_log_2D.png -------------------------------------------------------------------------------- /code/UnitTest/specs.py: -------------------------------------------------------------------------------- 1 | # specs.py 2 | """Python Essentials: Unit Testing. 3 | 4 | 5 | 6 | """ 7 | 8 | 9 | def add(a, b): 10 | """Add two numbers.""" 11 | return a + b 12 | 13 | 14 | def divide(a, b): 15 | """Divide two numbers, raising an error if the second number is zero.""" 16 | if b == 0: 17 | raise ZeroDivisionError("second input cannot be zero") 18 | return a / b 19 | 20 | 21 | # Problem 1 22 | def smallest_factor(n): 23 | """Return the smallest prime factor of the positive integer n.""" 24 | if n == 1: 25 | return 1 26 | for i in range(2, int(n**0.5)): 27 | if n % i == 0: 28 | return i 29 | return n 30 | 31 | 32 | # Problem 2 33 | def month_length(month, leap_year=False): 34 | """Return the number of days in the given month.""" 35 | if month in {"September", "April", "June", "November"}: 36 | return 30 37 | elif month in { 38 | "January", 39 | "March", 40 | "May", 41 | "July", 42 | "August", 43 | "October", 44 | "December", 45 | }: 46 | return 31 47 | if month == "February": 48 | if not leap_year: 49 | return 28 50 | else: 51 | return 29 52 | else: 53 | return None 54 | 55 | 56 | # Problem 3 57 | def operate(a, b, oper): 58 | """Apply an arithmetic operation to a and b.""" 59 | if type(oper) is not str: 60 | raise TypeError("oper must be a string") 61 | elif oper == "+": 62 | return a + b 63 | elif oper == "-": 64 | return a - b 65 | elif oper == "*": 66 | return a * b 67 | elif oper == "/": 68 | if b == 0: 69 | raise ZeroDivisionError("division by zero is undefined") 70 | return a / b 71 | raise ValueError("oper must be one of '+', '/', '-', or '*'") 72 | 73 | 74 | # Problem 4 75 | class Fraction(object): 76 | """Reduced fraction class with integer numerator and denominator.""" 77 | 78 | def __init__(self, numerator, denominator): 79 | if denominator == 0: 80 | raise ZeroDivisionError("denominator cannot be zero") 81 | elif type(numerator) is not int or type(denominator) is not int: 82 | raise TypeError("numerator and denominator must be integers") 83 | 84 | def gcd(a, b): 85 | while b != 0: 86 | a, b = b, a % b 87 | return a 88 | 89 | common_factor = gcd(numerator, denominator) 90 | self.numer = numerator // common_factor 91 | self.denom = denominator // common_factor 92 | 93 | def __str__(self): 94 | if self.denom != 1: 95 | return "{}/{}".format(self.numer, self.denom) 96 | else: 97 | return str(self.numer) 98 | 99 | def __float__(self): 100 | return self.numer / self.denom 101 | 102 | def __eq__(self, other): 103 | if type(other) is Fraction: 104 | return self.numer == other.numer and self.denom == other.denom 105 | else: 106 | return float(self) == other 107 | 108 | def __add__(self, other): 109 | return Fraction( 110 | self.numer * other.numer + self.denom * other.denom, 111 | self.denom * other.denom, 112 | ) 113 | 114 | def __sub__(self, other): 115 | return Fraction( 116 | self.numer * other.numer - self.denom * other.denom, 117 | self.denom * other.denom, 118 | ) 119 | 120 | def __mul__(self, other): 121 | return Fraction(self.numer * other.numer, self.denom * other.denom) 122 | 123 | def __truediv__(self, other): 124 | if self.denom * other.numer == 0: 125 | raise ZeroDivisionError("cannot divide by zero") 126 | return Fraction(self.numer * other.denom, self.denom * other.numer) 127 | 128 | 129 | # Problem 6 130 | def count_sets(cards): 131 | """Return the number of sets in the provided Set hand. 132 | 133 | Parameters: 134 | cards (list(str)) a list of twelve cards as 4-bit integers in 135 | base 3 as strings, such as ["1022", "1122", ..., "1020"]. 136 | Returns: 137 | (int) The number of sets in the hand. 138 | Raises: 139 | ValueError: if the list does not contain a valid Set hand, meaning 140 | - there are not exactly 12 cards, 141 | - the cards are not all unique, 142 | - one or more cards does not have exactly 4 digits, or 143 | - one or more cards has a character other than 0, 1, or 2. 144 | """ 145 | raise NotImplementedError("Problem 6 Incomplete") 146 | 147 | 148 | def is_set(a, b, c): 149 | """Determine if the cards a, b, and c constitute a set. 150 | 151 | Parameters: 152 | a, b, c (str): string representations of 4-bit integers in base 3. 153 | For example, "1022", "1122", and "1020" (which is not a set). 154 | Returns: 155 | True if a, b, and c form a set, meaning the ith digit of a, b, 156 | and c are either the same or all different for i=1,2,3,4. 157 | False if a, b, and c do not form a set. 158 | """ 159 | raise NotImplementedError("Problem 6 Incomplete") 160 | -------------------------------------------------------------------------------- /code/UnitTest/test_specs.py: -------------------------------------------------------------------------------- 1 | # test_specs.py 2 | """Python Essentials: Unit Testing. 3 | 4 | 5 | 6 | """ 7 | 8 | import specs 9 | import pytest 10 | 11 | 12 | def test_add(): 13 | assert specs.add(1, 3) == 4, "failed on positive integers" 14 | assert specs.add(-5, -7) == -12, "failed on negative integers" 15 | assert specs.add(-6, 14) == 8 16 | 17 | 18 | def test_divide(): 19 | assert specs.divide(4, 2) == 2, "integer division" 20 | assert specs.divide(5, 4) == 1.25, "float division" 21 | with pytest.raises(ZeroDivisionError) as excinfo: 22 | specs.divide(4, 0) 23 | assert excinfo.value.args[0] == "second input cannot be zero" 24 | 25 | 26 | # Problem 1: write a unit test for specs.smallest_factor(), then correct it. 27 | 28 | 29 | # Problem 2: write a unit test for specs.month_length(). 30 | 31 | 32 | # Problem 3: write a unit test for specs.operate(). 33 | 34 | 35 | # Problem 4: write unit tests for specs.Fraction, then correct it. 36 | @pytest.fixture 37 | def set_up_fractions(): 38 | frac_1_3 = specs.Fraction(1, 3) 39 | frac_1_2 = specs.Fraction(1, 2) 40 | frac_n2_3 = specs.Fraction(-2, 3) 41 | return frac_1_3, frac_1_2, frac_n2_3 42 | 43 | 44 | def test_fraction_init(set_up_fractions): 45 | frac_1_3, frac_1_2, frac_n2_3 = set_up_fractions 46 | assert frac_1_3.numer == 1 47 | assert frac_1_2.denom == 2 48 | assert frac_n2_3.numer == -2 49 | frac = specs.Fraction(30, 42) 50 | assert frac.numer == 5 51 | assert frac.denom == 7 52 | 53 | 54 | def test_fraction_str(set_up_fractions): 55 | frac_1_3, frac_1_2, frac_n2_3 = set_up_fractions 56 | assert str(frac_1_3) == "1/3" 57 | assert str(frac_1_2) == "1/2" 58 | assert str(frac_n2_3) == "-2/3" 59 | 60 | 61 | def test_fraction_float(set_up_fractions): 62 | frac_1_3, frac_1_2, frac_n2_3 = set_up_fractions 63 | assert float(frac_1_3) == 1 / 3.0 64 | assert float(frac_1_2) == 0.5 65 | assert float(frac_n2_3) == -2 / 3.0 66 | 67 | 68 | def test_fraction_eq(set_up_fractions): 69 | frac_1_3, frac_1_2, frac_n2_3 = set_up_fractions 70 | assert frac_1_2 == specs.Fraction(1, 2) 71 | assert frac_1_3 == specs.Fraction(2, 6) 72 | assert frac_n2_3 == specs.Fraction(8, -12) 73 | 74 | 75 | # Problem 5: Write test cases for Set. 76 | -------------------------------------------------------------------------------- /code/UnixShell1/Shell1.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/code/UnixShell1/Shell1.zip -------------------------------------------------------------------------------- /code/UnixShell1/unixshell1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # remove any previously unzipped copies of Shell1/ 4 | if [ -d Shell1 ]; 5 | then 6 | echo "Removing old copies of Shell1/..." 7 | rm -r Shell1 8 | echo "Done" 9 | fi 10 | 11 | # unzip a fresh copy of Shell1/ 12 | echo "Unzipping Shell1.zip..." 13 | unzip -q Shell1 14 | echo "Done" 15 | 16 | : ' Problem 1: In the space below, write commands to change into the 17 | Shell1/ directory and print a string telling you the current working 18 | directory. ' 19 | 20 | 21 | 22 | : ' Problem 2: Use ls with flags to print one list of the contents of 23 | Shell1/, including hidden files and folders, listing contents in long 24 | format, and sorting output by file size. ' 25 | 26 | 27 | : ' Problem 3: Inside the Shell1/ directory, delete the Audio/ folder 28 | along with all its contents. Create Documents/, Photos/, and 29 | Python/ directories. Rename the Random/ folder as Files/. ' 30 | 31 | 32 | 33 | : ' Problem 4: Using wildcards, move all the .jpg files to the Photos/ 34 | directory, all the .txt files to the Documents/ directory, and all the 35 | .py files to the Python/ directory. ' 36 | 37 | 38 | 39 | : ' Problem 5: Move organize_photos.sh to Scripts/, add executable 40 | permissions to the script, and run the script. ' 41 | 42 | 43 | 44 | : ' Problem 6: Copy img_649.jpg from UnixShell1/ to Shell1/Photos, making 45 | sure to leave a copy of the file in UnixShell1/.' 46 | 47 | 48 | 49 | # remove any old copies of UnixShell1.tar.gz 50 | if [ ! -d Shell1 ]; 51 | then 52 | cd .. 53 | fi 54 | 55 | if [ -f UnixShell1.tar.gz ]; 56 | then 57 | echo "Removing old copies of UnixShell1.tar.gz..." 58 | rm -v UnixShell1.tar.gz 59 | echo "Done" 60 | fi 61 | 62 | # archive and compress the Shell1/ directory 63 | echo "Compressing Shell1/ Directory..." 64 | tar -zcpf UnixShell1.tar.gz Shell1/* 65 | echo "Done" 66 | -------------------------------------------------------------------------------- /code/gmm/distributions.py: -------------------------------------------------------------------------------- 1 | """ 2 | ------------------------------------------------------------------------ 3 | This module contains the functions for probability density functions of 4 | continuous PDF's. 5 | 6 | This Python module defines the following function(s): 7 | GA_pdf() 8 | GG_pdf() 9 | GB2_pdf() 10 | ------------------------------------------------------------------------ 11 | """ 12 | # Import packages 13 | import numpy as np 14 | import scipy.special as spc 15 | 16 | 17 | """ 18 | ------------------------------------------------------------------------ 19 | Functions 20 | ------------------------------------------------------------------------ 21 | """ 22 | 23 | 24 | def LN_pdf(xvals, mu, sigma): 25 | """ 26 | -------------------------------------------------------------------- 27 | This function gives the PDF of the lognormal distribution for xvals 28 | given mu and sigma 29 | 30 | (LN): f(x; mu, sigma) = (1 / (x * sigma * sqrt(2 * pi))) * 31 | exp((-1 / 2) * (((log(x) - mu) / sigma) ** 2)) 32 | x in [0, infty), mu in (-infty, infty), sigma > 0 33 | -------------------------------------------------------------------- 34 | INPUTS: 35 | xvals = (N,) vector, data 36 | mu = scalar, mean of the ln(x) 37 | sigma = scalar > 0, standard deviation of ln(x) 38 | 39 | OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: None 40 | 41 | OBJECTS CREATED WITHIN FUNCTION: 42 | pdf_vals = (N,) vector, probability of each observation given 43 | the parameter values 44 | 45 | FILES CREATED BY THIS FUNCTION: None 46 | 47 | RETURNS: pdf_vals 48 | -------------------------------------------------------------------- 49 | """ 50 | pdf_vals = np.float64( 51 | ( 52 | (1 / (np.sqrt(2 * np.pi) * sigma * xvals)) 53 | * np.exp((-1.0 / 2.0) * (((np.log(xvals) - mu) / sigma) ** 2)) 54 | ) 55 | ) 56 | 57 | return pdf_vals 58 | 59 | 60 | def GA_pdf(xvals, alpha, beta): 61 | """ 62 | -------------------------------------------------------------------- 63 | Returns the PDF values from the two-parameter gamma (GA) 64 | distribution. See McDonald and Xu (1995). 65 | 66 | (GA): f(x; alpha, beta) = (1 / ((beta ** alpha) * 67 | spc.gamma(alpha))) * (x ** (alpha - 1)) * (e ** (-x / beta)) 68 | x in [0, infty), alpha, beta > 0 69 | -------------------------------------------------------------------- 70 | INPUTS: 71 | xvals = (N,) vector, values in the support of gamma distribution 72 | alpha = scalar > 0, gamma distribution parameter 73 | beta = scalar > 0, gamma distribution parameter 74 | 75 | OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: 76 | spc.gamma() 77 | 78 | OBJECTS CREATED WITHIN FUNCTION: 79 | pdf_vals = (N,) vector, pdf values from gamma distribution 80 | corresponding to xvals given parameters alpha and beta 81 | 82 | FILES CREATED BY THIS FUNCTION: None 83 | 84 | RETURNS: pdf_vals 85 | -------------------------------------------------------------------- 86 | """ 87 | pdf_vals = np.float64( 88 | (1 / ((beta**alpha) * spc.gamma(alpha))) 89 | * (xvals ** (alpha - 1)) 90 | * np.exp(-xvals / beta) 91 | ) 92 | 93 | return pdf_vals 94 | 95 | 96 | def GG_pdf(xvals, alpha, beta, mm): 97 | """ 98 | -------------------------------------------------------------------- 99 | Returns the PDF values from the three-parameter generalized gamma 100 | (GG) distribution. See McDonald and Xu (1995). 101 | 102 | (GG): f(x; alpha, beta, m) = 103 | (m / ((beta ** alpha) * spc.gamma(alpha/m))) * 104 | (x ** (alpha - 1)) * (e ** -((x / beta) ** m)) 105 | x in [0, infty), alpha, beta, m > 0 106 | -------------------------------------------------------------------- 107 | INPUTS: 108 | xvals = (N,) vector, values in the support of generalized gamma (GG) 109 | distribution 110 | alpha = scalar > 0, generalized gamma (GG) distribution parameter 111 | beta = scalar > 0, generalized gamma (GG) distribution parameter 112 | mm = scalar > 0, generalized gamma (GG) distribution parameter 113 | 114 | OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: 115 | spc.gamma() 116 | 117 | OBJECTS CREATED WITHIN FUNCTION: 118 | pdf_vals = (N,) vector, pdf values from generalized gamma 119 | distribution corresponding to xvals given parameters 120 | alpha, beta, and mm 121 | 122 | FILES CREATED BY THIS FUNCTION: None 123 | 124 | RETURNS: pdf_vals 125 | -------------------------------------------------------------------- 126 | """ 127 | pdf_vals = np.float64( 128 | (mm / ((beta**alpha) * spc.gamma(alpha / mm))) 129 | * (xvals ** (alpha - 1)) 130 | * np.exp(-((xvals / beta) ** mm)) 131 | ) 132 | 133 | return pdf_vals 134 | 135 | 136 | def GB2_pdf(xvals, aa, bb, pp, qq): 137 | """ 138 | -------------------------------------------------------------------- 139 | Returns the PDF values from the four-parameter generalized beta 2 140 | (GB2) distribution. See McDonald and Xu (1995). 141 | 142 | (GB2): f(x; a, b, p, q) = (a * (x ** ((a*p) - 1))) / 143 | ((b ** (a * p)) * spc.beta(p, q) * 144 | ((1 + ((x / b) ** a)) ** (p + q))) 145 | x in [0, infty), alpha, beta, m > 0 146 | -------------------------------------------------------------------- 147 | INPUTS: 148 | xvals = (N,) vector, values in the support of generalized beta 2 149 | (GB2) distribution 150 | aa = scalar > 0, generalized beta 2 (GB2) distribution parameter 151 | bb = scalar > 0, generalized beta 2 (GB2) distribution parameter 152 | pp = scalar > 0, generalized beta 2 (GB2) distribution parameter 153 | qq = scalar > 0, generalized beta 2 (GB2) distribution parameter 154 | 155 | OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: 156 | spc.beta() 157 | 158 | OBJECTS CREATED WITHIN FUNCTION: 159 | pdf_vals = (N,) vector, pdf values from generalized beta 2 (GB2) 160 | distribution corresponding to xvals given parameters aa, 161 | bb, pp, and qq 162 | 163 | FILES CREATED BY THIS FUNCTION: None 164 | 165 | RETURNS: pdf_vals 166 | -------------------------------------------------------------------- 167 | """ 168 | pdf_vals = np.float64( 169 | (aa * (xvals ** (aa * pp - 1))) 170 | / ( 171 | (bb ** (aa * pp)) 172 | * spc.beta(pp, qq) 173 | * ((1 + ((xvals / bb) ** aa)) ** (pp + qq)) 174 | ) 175 | ) 176 | 177 | return pdf_vals 178 | -------------------------------------------------------------------------------- /code/junk_funcs.py: -------------------------------------------------------------------------------- 1 | """ 2 | ------------------------------------------------------------------------ 3 | This module contains a junk placeholder function for testing purposes. 4 | ------------------------------------------------------------------------ 5 | """ 6 | 7 | 8 | def junk_func_add(arg1, arg2): 9 | """ 10 | This is just a junk function in this junk module in the `/code/` 11 | directory. We can delete this as soon as we have some real functions. 12 | """ 13 | junk_sum = arg1 + arg2 14 | 15 | return junk_sum 16 | -------------------------------------------------------------------------------- /code/mle/distributions.py: -------------------------------------------------------------------------------- 1 | """ 2 | ------------------------------------------------------------------------ 3 | This module contains the functions for probability density functions of 4 | continuous PDF's. 5 | 6 | This Python module defines the following function(s): 7 | GA_pdf() 8 | GG_pdf() 9 | GB2_pdf() 10 | ------------------------------------------------------------------------ 11 | """ 12 | # Import packages 13 | import numpy as np 14 | import scipy.special as spc 15 | 16 | 17 | """ 18 | ------------------------------------------------------------------------ 19 | Functions 20 | ------------------------------------------------------------------------ 21 | """ 22 | 23 | 24 | def LN_pdf(xvals, mu, sigma): 25 | """ 26 | -------------------------------------------------------------------- 27 | This function gives the PDF of the lognormal distribution for xvals 28 | given mu and sigma 29 | 30 | (LN): f(x; mu, sigma) = (1 / (x * sigma * sqrt(2 * pi))) * 31 | exp((-1 / 2) * (((log(x) - mu) / sigma) ** 2)) 32 | x in [0, infty), mu in (-infty, infty), sigma > 0 33 | -------------------------------------------------------------------- 34 | INPUTS: 35 | xvals = (N,) vector, data 36 | mu = scalar, mean of the ln(x) 37 | sigma = scalar > 0, standard deviation of ln(x) 38 | 39 | OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: None 40 | 41 | OBJECTS CREATED WITHIN FUNCTION: 42 | pdf_vals = (N,) vector, probability of each observation given 43 | the parameter values 44 | 45 | FILES CREATED BY THIS FUNCTION: None 46 | 47 | RETURNS: pdf_vals 48 | -------------------------------------------------------------------- 49 | """ 50 | pdf_vals = np.float64( 51 | ( 52 | (1 / (np.sqrt(2 * np.pi) * sigma * xvals)) 53 | * np.exp((-1.0 / 2.0) * (((np.log(xvals) - mu) / sigma) ** 2)) 54 | ) 55 | ) 56 | 57 | return pdf_vals 58 | 59 | 60 | def GA_pdf(xvals, alpha, beta): 61 | """ 62 | -------------------------------------------------------------------- 63 | Returns the PDF values from the two-parameter gamma (GA) 64 | distribution. See McDonald and Xu (1995). 65 | 66 | (GA): f(x; alpha, beta) = (1 / ((beta ** alpha) * 67 | spc.gamma(alpha))) * (x ** (alpha - 1)) * (e ** (-x / beta)) 68 | x in [0, infty), alpha, beta > 0 69 | -------------------------------------------------------------------- 70 | INPUTS: 71 | xvals = (N,) vector, values in the support of gamma distribution 72 | alpha = scalar > 0, gamma distribution parameter 73 | beta = scalar > 0, gamma distribution parameter 74 | 75 | OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: 76 | spc.gamma() 77 | 78 | OBJECTS CREATED WITHIN FUNCTION: 79 | pdf_vals = (N,) vector, pdf values from gamma distribution 80 | corresponding to xvals given parameters alpha and beta 81 | 82 | FILES CREATED BY THIS FUNCTION: None 83 | 84 | RETURNS: pdf_vals 85 | -------------------------------------------------------------------- 86 | """ 87 | pdf_vals = np.float64( 88 | (1 / ((beta**alpha) * spc.gamma(alpha))) 89 | * (xvals ** (alpha - 1)) 90 | * np.exp(-xvals / beta) 91 | ) 92 | 93 | return pdf_vals 94 | 95 | 96 | def GG_pdf(xvals, alpha, beta, mm): 97 | """ 98 | -------------------------------------------------------------------- 99 | Returns the PDF values from the three-parameter generalized gamma 100 | (GG) distribution. See McDonald and Xu (1995). 101 | 102 | (GG): f(x; alpha, beta, m) = 103 | (m / ((beta ** alpha) * spc.gamma(alpha/m))) * 104 | (x ** (alpha - 1)) * (e ** -((x / beta) ** m)) 105 | x in [0, infty), alpha, beta, m > 0 106 | -------------------------------------------------------------------- 107 | INPUTS: 108 | xvals = (N,) vector, values in the support of generalized gamma (GG) 109 | distribution 110 | alpha = scalar > 0, generalized gamma (GG) distribution parameter 111 | beta = scalar > 0, generalized gamma (GG) distribution parameter 112 | mm = scalar > 0, generalized gamma (GG) distribution parameter 113 | 114 | OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: 115 | spc.gamma() 116 | 117 | OBJECTS CREATED WITHIN FUNCTION: 118 | pdf_vals = (N,) vector, pdf values from generalized gamma 119 | distribution corresponding to xvals given parameters 120 | alpha, beta, and mm 121 | 122 | FILES CREATED BY THIS FUNCTION: None 123 | 124 | RETURNS: pdf_vals 125 | -------------------------------------------------------------------- 126 | """ 127 | pdf_vals = np.float64( 128 | (mm / ((beta**alpha) * spc.gamma(alpha / mm))) 129 | * (xvals ** (alpha - 1)) 130 | * np.exp(-((xvals / beta) ** mm)) 131 | ) 132 | 133 | return pdf_vals 134 | 135 | 136 | def GB2_pdf(xvals, aa, bb, pp, qq): 137 | """ 138 | -------------------------------------------------------------------- 139 | Returns the PDF values from the four-parameter generalized beta 2 140 | (GB2) distribution. See McDonald and Xu (1995). 141 | 142 | (GB2): f(x; a, b, p, q) = (a * (x ** ((a*p) - 1))) / 143 | ((b ** (a * p)) * spc.beta(p, q) * 144 | ((1 + ((x / b) ** a)) ** (p + q))) 145 | x in [0, infty), alpha, beta, m > 0 146 | -------------------------------------------------------------------- 147 | INPUTS: 148 | xvals = (N,) vector, values in the support of generalized beta 2 149 | (GB2) distribution 150 | aa = scalar > 0, generalized beta 2 (GB2) distribution parameter 151 | bb = scalar > 0, generalized beta 2 (GB2) distribution parameter 152 | pp = scalar > 0, generalized beta 2 (GB2) distribution parameter 153 | qq = scalar > 0, generalized beta 2 (GB2) distribution parameter 154 | 155 | OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: 156 | spc.beta() 157 | 158 | OBJECTS CREATED WITHIN FUNCTION: 159 | pdf_vals = (N,) vector, pdf values from generalized beta 2 (GB2) 160 | distribution corresponding to xvals given parameters aa, 161 | bb, pp, and qq 162 | 163 | FILES CREATED BY THIS FUNCTION: None 164 | 165 | RETURNS: pdf_vals 166 | -------------------------------------------------------------------- 167 | """ 168 | pdf_vals = np.float64( 169 | (aa * (xvals ** (aa * pp - 1))) 170 | / ( 171 | (bb ** (aa * pp)) 172 | * spc.beta(pp, qq) 173 | * ((1 + ((xvals / bb) ** aa)) ** (pp + qq)) 174 | ) 175 | ) 176 | 177 | return pdf_vals 178 | -------------------------------------------------------------------------------- /data/Matplotlib3/orbits.npz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/data/Matplotlib3/orbits.npz -------------------------------------------------------------------------------- /data/Pandas1/budget.csv: -------------------------------------------------------------------------------- 1 | ,Rent,Utilities,Groceries,Dining Out,Gas,Out With Friends,Netflix 2 | 1/15,700.0,90.0,163,31.0,,25.0, 3 | 2/15,700.0,90.0,150,34.0,,25.0, 4 | 3/15,700.0,90.0,145,32.0,,29.0, 5 | 4/15,700.0,82.0,174,35.0,,26.0, 6 | 5/15,700.0,82.0,171,40.0,,23.0, 7 | 6/15,700.0,82.0,141,37.0,,27.0, 8 | 7/15,700.0,82.0,171,35.0,,27.0, 9 | 8/15,700.0,82.0,137,36.0,,20.0, 10 | 9/15,700.0,82.0,145,40.0,,27.0, 11 | 10/15,700.0,92.0,175,40.0,,23.0, 12 | 11/15,700.0,92.0,155,33.0,,, 13 | 12/15,700.0,92.0,140,34.0,,24.0, 14 | 1/16,750.0,92.0,158,,,22.0, 15 | 2/16,750.0,92.0,136,36.0,,22.0, 16 | 3/16,750.0,92.0,167,30.0,,29.0, 17 | 4/16,750.0,85.0,130,31.0,,22.0, 18 | 5/16,750.0,85.0,163,30.0,,, 19 | 6/16,750.0,85.0,161,30.0,,24.0, 20 | 7/16,750.0,85.0,170,34.0,,25.0, 21 | 8/16,750.0,85.0,131,38.0,,23.0, 22 | 9/16,750.0,85.0,152,39.0,,29.0, 23 | 10/16,750.0,91.0,133,36.0,,23.0, 24 | 11/16,750.0,91.0,130,34.0,,21.0, 25 | 12/16,750.0,91.0,160,32.0,28.0,23.0, 26 | 1/17,750.0,91.0,148,40.0,31.0,, 27 | 2/17,750.0,91.0,148,34.0,28.0,27.0, 28 | 3/17,750.0,91.0,145,30.0,29.0,28.0, 29 | 4/17,750.0,80.0,178,34.0,31.0,25.0, 30 | 5/17,750.0,80.0,179,,30.0,26.0, 31 | 6/17,750.0,80.0,171,30.0,31.0,22.0, 32 | 7/17,775.0,80.0,131,31.0,29.0,, 33 | 8/17,775.0,80.0,155,,33.0,26.0,8 34 | 9/17,775.0,80.0,153,31.0,30.0,27.0,8 35 | 10/17,775.0,95.0,177,30.0,29.0,27.0,8 36 | 11/17,775.0,95.0,143,38.0,34.0,21.0,8 37 | 12/17,775.0,95.0,152,30.0,46.0,,8 38 | 1/18,775.0,95.0,137,36.0,34.0,23.0,8 39 | 2/18,775.0,95.0,146,31.0,32.0,23.0,8 40 | 3/18,775.0,95.0,152,32.0,34.0,22.0,8 41 | 4/18,775.0,82.0,157,,32.0,21.0,8 42 | 5/18,800.0,82.0,134,39.0,35.0,24.0,8 43 | 6/18,800.0,82.0,177,34.0,33.0,27.0,8 44 | 7/18,800.0,82.0,140,31.0,30.0,24.0,8 45 | 8/18,800.0,82.0,172,31.0,30.0,26.0,8 46 | 9/18,800.0,82.0,137,,31.0,28.0,8 47 | 10/18,800.0,90.0,170,34.0,33.0,,8 48 | 11/18,800.0,90.0,174,37.0,30.0,23.0,8 49 | 12/18,800.0,90.0,135,34.0,32.0,22.0,8 50 | -------------------------------------------------------------------------------- /data/Pandas1/crime_data.csv: -------------------------------------------------------------------------------- 1 | Year,Population,Total,Violent,Property,Murder,Forcible Rape,Robbery,Aggravated Assault,Burglary,Larceny,Vehicle Theft 2 | 1960,179323175,3384200,288460,3095700,9110,17190,107840,154320,912100,1855400,328200 3 | 1961,182992000,3488000,289390,3198600,8740,17220,106670,156760,949600,1913000,336000 4 | 1962,185771000,3752200,301510,3450700,8530,17550,110860,164570,994300,2089600,366800 5 | 1963,188483000,4109500,316970,3792500,8640,17650,116470,174210,1086400,2297800,408300 6 | 1964,191141000,4564600,364220,4200400,9360,21420,130390,203050,1213200,2514400,472800 7 | 1965,193526000,4739400,387390,4352000,9960,23410,138690,215330,1282500,2572600,496900 8 | 1966,195576000,5223500,430180,4793300,11040,25820,157990,235330,1410100,2822000,561200 9 | 1967,197457000,5903400,499930,5403500,12240,27620,202910,257160,1632100,3111600,659800 10 | 1968,199399000,6720200,595010,6125200,13800,31670,262840,286700,1858900,3482700,783600 11 | 1969,201385000,7410900,661870,6749000,14760,37170,298850,311090,1981900,3888600,878500 12 | 1970,203235298,8098000,738820,7359200,16000,37990,349860,334970,2205000,4225800,928400 13 | 1971,206212000,8588200,816500,7771700,17780,42260,387700,368760,2399300,4424200,948200 14 | 1972,208230000,8248800,834900,7413900,18670,46850,376290,393090,2375500,4151200,887200 15 | 1973,209851000,8718100,875910,7842200,19640,51400,384220,420650,2565500,4347900,928800 16 | 1974,211392000,10253400,974720,9278700,20710,55400,442400,456210,3039200,5262500,977100 17 | 1975,213124000,11292400,1039710,10252700,20510,56090,470500,492620,3265300,5977700,1009600 18 | 1976,214659000,11349700,1004210,10345500,18780,57080,427810,500530,3108700,6270800,966000 19 | 1977,216332000,10984500,1029580,9955000,19120,63500,412610,534350,3071500,5905700,977700 20 | 1978,218059000,11209000,1085550,10123400,19560,67610,426930,571460,3128300,5991000,1004100 21 | 1979,220099000,12249500,1208030,11041500,21460,76390,480700,629480,3327700,6601000,1112800 22 | 1980,225349264,13408300,1344520,12063700,23040,82990,565840,672650,3795200,7136900,1131700 23 | 1981,229146000,13423800,1361820,12061900,22520,82500,592910,663900,3779700,7194400,1087800 24 | 1982,231534000,12974400,1322390,11652000,21010,78770,553130,669480,3447100,7142500,1062400 25 | 1983,233981000,12108600,1258090,10850500,19310,78920,506570,653290,3129900,6712800,1007900 26 | 1984,236158000,11881800,1273280,10608500,18690,84230,485010,685350,2984400,6591900,1032200 27 | 1985,238740000,12431400,1328800,11102600,18980,88670,497870,723250,3073300,6926400,1102900 28 | 1986,240132887,13211869,1489169,11722700,20613,91459,542775,834322,3241410,7257153,1224137 29 | 1987,242282918,13508700,1483999,12024700,20096,91110,517704,855088,3236184,7499900,1288674 30 | 1988,245807000,13923100,1566220,12356900,20680,92490,542970,910090,3218100,7705900,1432900 31 | 1989,248239000,14251400,1646040,12605400,21500,94500,578330,951710,3168200,7872400,1564800 32 | 1990,248709873,14475600,1820130,12655500,23440,102560,639270,1054860,3073900,7945700,1635900 33 | 1991,252177000,14872900,1911770,12961100,24700,106590,687730,1092740,3157200,8142200,1661700 34 | 1992,255082000,14438200,1932270,12505900,23760,109060,672480,1126970,2979900,7915200,1610800 35 | 1993,257908000,14144800,1926020,12218800,24530,106010,659870,1135610,2834800,7820900,1563100 36 | 1994,260341000,13989500,1857670,12131900,23330,102220,618950,1113180,2712800,7879800,1539300 37 | 1995,262755000,13862700,1798790,12063900,21610,97470,580510,1099210,2593800,7997700,1472400 38 | 1996,265228572,13493863,1688540,11805300,19650,96250,535590,1037050,2506400,7904700,1394200 39 | 1997,267637000,13194571,1634770,11558175,18208,96153,498534,1023201,2460526,7743760,1354189 40 | 1998,270296000,12475634,1531044,10944590,16914,93103,446625,974402,2329950,7373886,1240754 41 | 1999,272690813,11634378,1426044,10208334,15522,89411,409371,911740,2100739,6955520,1152075 42 | 2000,281421906,11608072,1425486,10182586,15586,90178,408016,911706,2050992,6971590,1160002 43 | 2001,285317559,11876669,1439480,10437480,16037,90863,423557,909023,2116531,7092267,1228391 44 | 2002,287973924,11878954,1423677,10455277,16229,95235,420806,891407,2151252,7057370,1246646 45 | 2003,290690788,11826538,1383676,10442862,16528,93883,414235,859030,2154834,7026802,1261226 46 | 2004,293656842,11679474,1360088,10319386,16148,95089,401470,847381,2144446,6937089,1237851 47 | 2005,296507061,11565499,1390745,10174754,16740,94347,417438,862220,2155448,6783447,1235859 48 | 2006,299398484,11401511,1418043,9983568,17030,92757,447403,860853,2183746,6607013,1192809 49 | 2007,301621157,11251828,1408337,9843481,16929,90427,445125,855856,2176140,6568572,1095769 50 | 2008,304374846,11160543,1392628,9767915,16442,90479,443574,842134,2228474,6588046,958629 51 | 2009,307006550,10762956,1325896,9337060,15399,89241,408742,812514,2203313,6338095,795652 52 | 2010,309330219,10363873,1251248,9112625,14772,85593,369089,781844,2168457,6204601,739565 53 | 2011,311587816,10258774,1206031,9052743,14661,84175,354772,752423,2185140,6151095,716508 54 | 2012,313873685,10219059,1217067,9001992,14866,85141,355051,762009,2109932,6168874,723186 55 | 2013,316497531,9850445,1199684,8650761,14319,82109,345095,726575,1931835,6018632,700294 56 | 2014,318907401,9395195,1186185,8209010,14164,84864,322905,731089,1713153,5809054,686803 57 | 2015,320896618,9258298,1234183,8024115,15883,91261,328109,764057,1587564,5723488,713063 58 | 2016,323127513,9202093,1283058,7919035,17250,95730,332198,803007,1515096,5638455,765484 59 | -------------------------------------------------------------------------------- /data/Pandas1/paychecks.csv: -------------------------------------------------------------------------------- 1 | 1122.26 2 | 921.03 3 | 962.46 4 | 1035.97 5 | 1078.59 6 | 1110.97 7 | 1121.91 8 | 992.83 9 | 1103.23 10 | 944.66 11 | 1030.07 12 | 942.35 13 | 909.83 14 | 1125.79 15 | 947.21 16 | 1067.83 17 | 991.64 18 | 963.2 19 | 912.61 20 | 1018.91 21 | 997.93 22 | 1129.61 23 | 963.64 24 | 1009.76 25 | 984.89 26 | 1033.27 27 | 934.76 28 | 1122.1 29 | 1032.46 30 | 999.56 31 | 1021.88 32 | 1120.12 33 | 1007.78 34 | 1101.05 35 | 1110.52 36 | 1120.5 37 | 1015.99 38 | 1104.89 39 | 1049.28 40 | 923.36 41 | 1051.23 42 | 986.03 43 | 986.25 44 | 923.27 45 | 906.94 46 | 904.5 47 | 913.96 48 | 1045.15 49 | 1114.54 50 | 951.76 51 | 1069.41 52 | 1061.46 53 | 1100.81 54 | 1075.79 55 | 1129.35 56 | 994.7 57 | 937.77 58 | 1046.64 59 | 1057.79 60 | 985.75 61 | 1080.08 62 | 1015.01 63 | 1116.73 64 | 982.53 65 | 910.1 66 | 920.01 67 | 912.25 68 | 1109.19 69 | 1011.6 70 | 1126.08 71 | 1073.42 72 | 1068.5 73 | 1031.05 74 | 1102.34 75 | 928.88 76 | 1005.04 77 | 1021.27 78 | 1105.64 79 | 969.72 80 | 1025.93 81 | 1042.03 82 | 955.21 83 | 996.53 84 | 900.44 85 | 1104.4 86 | 935.0 87 | 1045.75 88 | 949.59 89 | 1095.53 90 | 1018.39 91 | 1027.08 92 | 1005.9 93 | 963.29 94 | -------------------------------------------------------------------------------- /data/Pandas3/mammal_sleep.csv: -------------------------------------------------------------------------------- 1 | name,genus,vore,order,sleep_total,sleep_rem,sleep_cycle 2 | Cheetah,Acinonyx,carni,Carnivora,12.1,, 3 | Owl monkey,Aotus,omni,Primates,17.0,1.8, 4 | Mountain beaver,Aplodontia,herbi,Rodentia,14.4,2.4, 5 | Greater short-tailed shrew,Blarina,omni,Soricomorpha,14.9,2.3,0.133333333 6 | Cow,Bos,herbi,Artiodactyla,4.0,0.7,0.666666667 7 | Three-toed sloth,Bradypus,herbi,Pilosa,14.4,2.2,0.7666666670000001 8 | Northern fur seal,Callorhinus,carni,Carnivora,8.7,1.4,0.38333333299999994 9 | Vesper mouse,Calomys,,Rodentia,7.0,, 10 | Dog,Canis,carni,Carnivora,10.1,2.9,0.333333333 11 | Roe deer,Capreolus,herbi,Artiodactyla,3.0,, 12 | Goat,Capri,herbi,Artiodactyla,5.3,0.6, 13 | Guinea pig,Cavis,herbi,Rodentia,9.4,0.8,0.21666666699999998 14 | Grivet,Cercopithecus,omni,Primates,10.0,0.7, 15 | Chinchilla,Chinchilla,herbi,Rodentia,12.5,1.5,0.11666666699999999 16 | Star-nosed mole,Condylura,omni,Soricomorpha,10.3,2.2, 17 | African giant pouched rat,Cricetomys,omni,Rodentia,8.3,2.0, 18 | Lesser short-tailed shrew,Cryptotis,omni,Soricomorpha,9.1,1.4,0.15 19 | Long-nosed armadillo,Dasypus,carni,Cingulata,17.4,3.1,0.38333333299999994 20 | Tree hyrax,Dendrohyrax,herbi,Hyracoidea,5.3,0.5, 21 | North American Opossum,Didelphis,omni,Didelphimorphia,18.0,4.9,0.333333333 22 | Asian elephant,Elephas,herbi,Proboscidea,3.9,, 23 | Big brown bat,Eptesicus,insecti,Chiroptera,19.7,3.9,0.11666666699999999 24 | Horse,Equus,herbi,Perissodactyla,2.9,0.6,1.0 25 | Donkey,Equus,herbi,Perissodactyla,3.1,0.4, 26 | European hedgehog,Erinaceus,omni,Erinaceomorpha,10.1,3.5,0.283333333 27 | Patas monkey,Erythrocebus,omni,Primates,10.9,1.1, 28 | Western american chipmunk,Eutamias,herbi,Rodentia,14.9,, 29 | Domestic cat,Felis,carni,Carnivora,12.5,3.2,0.41666666700000005 30 | Galago,Galago,omni,Primates,9.8,1.1,0.55 31 | Giraffe,Giraffa,herbi,Artiodactyla,1.9,0.4, 32 | Pilot whale,Globicephalus,carni,Cetacea,2.7,0.1, 33 | Gray seal,Haliochoerus,carni,Carnivora,6.2,1.5, 34 | Gray hyrax,Heterohyrax,herbi,Hyracoidea,6.3,0.6, 35 | Human,Homo,omni,Primates,8.0,1.9,1.5 36 | Mongoose lemur,Lemur,herbi,Primates,9.5,0.9, 37 | African elephant,Loxodonta,herbi,Proboscidea,3.3,, 38 | Thick-tailed opposum,Lutreolina,carni,Didelphimorphia,19.4,6.6, 39 | Macaque,Macaca,omni,Primates,10.1,1.2,0.75 40 | Mongolian gerbil,Meriones,herbi,Rodentia,14.2,1.9, 41 | Golden hamster,Mesocricetus,herbi,Rodentia,14.3,3.1,0.2 42 | Vole ,Microtus,herbi,Rodentia,12.8,, 43 | House mouse,Mus,herbi,Rodentia,12.5,1.4,0.18333333300000001 44 | Little brown bat,Myotis,insecti,Chiroptera,19.9,2.0,0.2 45 | Round-tailed muskrat,Neofiber,herbi,Rodentia,14.6,, 46 | Slow loris,Nyctibeus,carni,Primates,11.0,, 47 | Degu,Octodon,herbi,Rodentia,7.7,0.9, 48 | Northern grasshopper mouse,Onychomys,carni,Rodentia,14.5,, 49 | Rabbit,Oryctolagus,herbi,Lagomorpha,8.4,0.9,0.41666666700000005 50 | Sheep,Ovis,herbi,Artiodactyla,3.8,0.6, 51 | Chimpanzee,Pan,omni,Primates,9.7,1.4,1.4166666669999999 52 | Tiger,Panthera,carni,Carnivora,15.8,, 53 | Jaguar,Panthera,carni,Carnivora,10.4,, 54 | Lion,Panthera,carni,Carnivora,13.5,, 55 | Baboon,Papio,omni,Primates,9.4,1.0,0.666666667 56 | Desert hedgehog,Paraechinus,,Erinaceomorpha,10.3,2.7, 57 | Potto,Perodicticus,omni,Primates,11.0,, 58 | Deer mouse,Peromyscus,,Rodentia,11.5,, 59 | Phalanger,Phalanger,,Diprotodontia,13.7,1.8, 60 | Caspian seal,Phoca,carni,Carnivora,3.5,0.4, 61 | Common porpoise,Phocoena,carni,Cetacea,5.6,, 62 | Potoroo,Potorous,herbi,Diprotodontia,11.1,1.5, 63 | Giant armadillo,Priodontes,insecti,Cingulata,18.1,6.1, 64 | Rock hyrax,Procavia,,Hyracoidea,5.4,0.5, 65 | Laboratory rat,Rattus,herbi,Rodentia,13.0,2.4,0.18333333300000001 66 | African striped mouse,Rhabdomys,omni,Rodentia,8.7,, 67 | Squirrel monkey,Saimiri,omni,Primates,9.6,1.4, 68 | Eastern american mole,Scalopus,insecti,Soricomorpha,8.4,2.1,0.166666667 69 | Cotton rat,Sigmodon,herbi,Rodentia,11.3,1.1,0.15 70 | Mole rat,Spalax,,Rodentia,10.6,2.4, 71 | Arctic ground squirrel,Spermophilus,herbi,Rodentia,16.6,, 72 | Thirteen-lined ground squirrel,Spermophilus,herbi,Rodentia,13.8,3.4,0.21666666699999998 73 | Golden-mantled ground squirrel,Spermophilus,herbi,Rodentia,15.9,3.0, 74 | Musk shrew,Suncus,,Soricomorpha,12.8,2.0,0.18333333300000001 75 | Pig,Sus,omni,Artiodactyla,9.1,2.4,0.5 76 | Short-nosed echidna,Tachyglossus,insecti,Monotremata,8.6,, 77 | Eastern american chipmunk,Tamias,herbi,Rodentia,15.8,, 78 | Brazilian tapir,Tapirus,herbi,Perissodactyla,4.4,1.0,0.9 79 | Tenrec,Tenrec,omni,Afrosoricida,15.6,2.3, 80 | Tree shrew,Tupaia,omni,Scandentia,8.9,2.6,0.233333333 81 | Bottle-nosed dolphin,Tursiops,carni,Cetacea,5.2,, 82 | Genet,Genetta,carni,Carnivora,6.3,1.3, 83 | Arctic fox,Vulpes,carni,Carnivora,12.5,, 84 | Red fox,Vulpes,carni,Carnivora,9.8,2.4,0.35 85 | -------------------------------------------------------------------------------- /data/basic_empirics/maketable1.dta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/data/basic_empirics/maketable1.dta -------------------------------------------------------------------------------- /data/gmm/Econ381totpts.txt: -------------------------------------------------------------------------------- 1 | 275.5 2 | 351.5 3 | 346.25 4 | 228.25 5 | 108.25 6 | 380.75 7 | 346.25 8 | 360.75 9 | 196 10 | 414.75 11 | 370.5 12 | 371.75 13 | 143.75 14 | 333.5 15 | 397.5 16 | 405.75 17 | 154.75 18 | 321 19 | 279 20 | 326.5 21 | 49.5 22 | 402.75 23 | 389.75 24 | 382.25 25 | 337.75 26 | 311 27 | 105.5 28 | 380.5 29 | 236 30 | 326.5 31 | 343.75 32 | 328.75 33 | 316.25 34 | 348.25 35 | 338.75 36 | 375.75 37 | 410 38 | 17 39 | 414.25 40 | 21.25 41 | 369.625 42 | 318.875 43 | 336.125 44 | 429.875 45 | 407.5 46 | 415.75 47 | 332.375 48 | 397 49 | 375.875 50 | 419.125 51 | 270.125 52 | 299.25 53 | 384.125 54 | 335 55 | 408.5 56 | 414.25 57 | 253.5 58 | 339.25 59 | 338.75 60 | 355.375 61 | 326.375 62 | 240.375 63 | 385 64 | 435 65 | 317.25 66 | 365.625 67 | 372.75 68 | 365.125 69 | 349.625 70 | 366.75 71 | 386.5 72 | 391.75 73 | 403 74 | 258.5 75 | 386 76 | 411 77 | 350.25 78 | 402.25 79 | 294.625 80 | 291.125 81 | 378.125 82 | 442.0 83 | 428.1 84 | 347.3 85 | 431.8 86 | 430.4 87 | 426.0 88 | 433.5 89 | 331.1 90 | 405.7 91 | 415.5 92 | 406.4 93 | 418.6 94 | 400.7 95 | 408.8 96 | 404.8 97 | 409.4 98 | 410.8 99 | 402.5 100 | 401.0 101 | 415.3 102 | 390.8 103 | 394.6 104 | 399.0 105 | 380.0 106 | 397.5 107 | 368.7 108 | 394.7 109 | 304.3 110 | 391.1 111 | 388.4 112 | 370.3 113 | 384.6 114 | 383.5 115 | 305.6 116 | 286.5 117 | 367.9 118 | 329.8 119 | 288.2 120 | 338.5 121 | 333.6 122 | 268.6 123 | 335.2 124 | 296.3 125 | 269.1 126 | 243.2 127 | 159.4 128 | 448.4 129 | 449.8 130 | 435.9 131 | 429.4 132 | 428.3 133 | 427.5 134 | 422.5 135 | 409.8 136 | 415.8 137 | 413.4 138 | 416.8 139 | 406.7 140 | 383.9 141 | 389.0 142 | 387.2 143 | 368.6 144 | 399.5 145 | 382.6 146 | 355.9 147 | 389.9 148 | 342.5 149 | 365.2 150 | 320.3 151 | 341.5 152 | 248.1 153 | 305.0 154 | 279.2 155 | 275.7 156 | 204.5 157 | 235.0 158 | 102.2 159 | 112.3 160 | 130.6 161 | 60.2 -------------------------------------------------------------------------------- /data/mle/Econ381totpts.txt: -------------------------------------------------------------------------------- 1 | 275.5 2 | 351.5 3 | 346.25 4 | 228.25 5 | 108.25 6 | 380.75 7 | 346.25 8 | 360.75 9 | 196 10 | 414.75 11 | 370.5 12 | 371.75 13 | 143.75 14 | 333.5 15 | 397.5 16 | 405.75 17 | 154.75 18 | 321 19 | 279 20 | 326.5 21 | 49.5 22 | 402.75 23 | 389.75 24 | 382.25 25 | 337.75 26 | 311 27 | 105.5 28 | 380.5 29 | 236 30 | 326.5 31 | 343.75 32 | 328.75 33 | 316.25 34 | 348.25 35 | 338.75 36 | 375.75 37 | 410 38 | 17 39 | 414.25 40 | 21.25 41 | 369.625 42 | 318.875 43 | 336.125 44 | 429.875 45 | 407.5 46 | 415.75 47 | 332.375 48 | 397 49 | 375.875 50 | 419.125 51 | 270.125 52 | 299.25 53 | 384.125 54 | 335 55 | 408.5 56 | 414.25 57 | 253.5 58 | 339.25 59 | 338.75 60 | 355.375 61 | 326.375 62 | 240.375 63 | 385 64 | 435 65 | 317.25 66 | 365.625 67 | 372.75 68 | 365.125 69 | 349.625 70 | 366.75 71 | 386.5 72 | 391.75 73 | 403 74 | 258.5 75 | 386 76 | 411 77 | 350.25 78 | 402.25 79 | 294.625 80 | 291.125 81 | 378.125 82 | 442.0 83 | 428.1 84 | 347.3 85 | 431.8 86 | 430.4 87 | 426.0 88 | 433.5 89 | 331.1 90 | 405.7 91 | 415.5 92 | 406.4 93 | 418.6 94 | 400.7 95 | 408.8 96 | 404.8 97 | 409.4 98 | 410.8 99 | 402.5 100 | 401.0 101 | 415.3 102 | 390.8 103 | 394.6 104 | 399.0 105 | 380.0 106 | 397.5 107 | 368.7 108 | 394.7 109 | 304.3 110 | 391.1 111 | 388.4 112 | 370.3 113 | 384.6 114 | 383.5 115 | 305.6 116 | 286.5 117 | 367.9 118 | 329.8 119 | 288.2 120 | 338.5 121 | 333.6 122 | 268.6 123 | 335.2 124 | 296.3 125 | 269.1 126 | 243.2 127 | 159.4 128 | 448.4 129 | 449.8 130 | 435.9 131 | 429.4 132 | 428.3 133 | 427.5 134 | 422.5 135 | 409.8 136 | 415.8 137 | 413.4 138 | 416.8 139 | 406.7 140 | 383.9 141 | 389.0 142 | 387.2 143 | 368.6 144 | 399.5 145 | 382.6 146 | 355.9 147 | 389.9 148 | 342.5 149 | 365.2 150 | 320.3 151 | 341.5 152 | 248.1 153 | 305.0 154 | 279.2 155 | 275.7 156 | 204.5 157 | 235.0 158 | 102.2 159 | 112.3 160 | 130.6 161 | 60.2 -------------------------------------------------------------------------------- /data/smm/Econ381totpts.txt: -------------------------------------------------------------------------------- 1 | 275.5 2 | 351.5 3 | 346.25 4 | 228.25 5 | 108.25 6 | 380.75 7 | 346.25 8 | 360.75 9 | 196 10 | 414.75 11 | 370.5 12 | 371.75 13 | 143.75 14 | 333.5 15 | 397.5 16 | 405.75 17 | 154.75 18 | 321 19 | 279 20 | 326.5 21 | 49.5 22 | 402.75 23 | 389.75 24 | 382.25 25 | 337.75 26 | 311 27 | 105.5 28 | 380.5 29 | 236 30 | 326.5 31 | 343.75 32 | 328.75 33 | 316.25 34 | 348.25 35 | 338.75 36 | 375.75 37 | 410 38 | 17 39 | 414.25 40 | 21.25 41 | 369.625 42 | 318.875 43 | 336.125 44 | 429.875 45 | 407.5 46 | 415.75 47 | 332.375 48 | 397 49 | 375.875 50 | 419.125 51 | 270.125 52 | 299.25 53 | 384.125 54 | 335 55 | 408.5 56 | 414.25 57 | 253.5 58 | 339.25 59 | 338.75 60 | 355.375 61 | 326.375 62 | 240.375 63 | 385 64 | 435 65 | 317.25 66 | 365.625 67 | 372.75 68 | 365.125 69 | 349.625 70 | 366.75 71 | 386.5 72 | 391.75 73 | 403 74 | 258.5 75 | 386 76 | 411 77 | 350.25 78 | 402.25 79 | 294.625 80 | 291.125 81 | 378.125 82 | 442.0 83 | 428.1 84 | 347.3 85 | 431.8 86 | 430.4 87 | 426.0 88 | 433.5 89 | 331.1 90 | 405.7 91 | 415.5 92 | 406.4 93 | 418.6 94 | 400.7 95 | 408.8 96 | 404.8 97 | 409.4 98 | 410.8 99 | 402.5 100 | 401.0 101 | 415.3 102 | 390.8 103 | 394.6 104 | 399.0 105 | 380.0 106 | 397.5 107 | 368.7 108 | 394.7 109 | 304.3 110 | 391.1 111 | 388.4 112 | 370.3 113 | 384.6 114 | 383.5 115 | 305.6 116 | 286.5 117 | 367.9 118 | 329.8 119 | 288.2 120 | 338.5 121 | 333.6 122 | 268.6 123 | 335.2 124 | 296.3 125 | 269.1 126 | 243.2 127 | 159.4 128 | 448.4 129 | 449.8 130 | 435.9 131 | 429.4 132 | 428.3 133 | 427.5 134 | 422.5 135 | 409.8 136 | 415.8 137 | 413.4 138 | 416.8 139 | 406.7 140 | 383.9 141 | 389.0 142 | 387.2 143 | 368.6 144 | 399.5 145 | 382.6 146 | 355.9 147 | 389.9 148 | 342.5 149 | 365.2 150 | 320.3 151 | 341.5 152 | 248.1 153 | 305.0 154 | 279.2 155 | 275.7 156 | 204.5 157 | 235.0 158 | 102.2 159 | 112.3 160 | 130.6 161 | 60.2 -------------------------------------------------------------------------------- /data/smm/usincmoms.txt: -------------------------------------------------------------------------------- 1 | 0.035190156 2500 0.041062064 7500 0.058859479 12500 0.056836107 17500 0.0585952 22500 0.054432836 27500 0.055060495 32500 0.050675146 37500 0.047858942 42500 0.04083908 47500 0.042697279 52500 0.03509931 57500 0.036602387 62500 0.031680225 67500 0.029780733 72500 0.028508899 77500 0.025073296 82500 0.021191725 87500 0.021422967 92500 0.018590247 97500 0.020869637 102500 0.014626089 107500 0.014229673 112500 0.01295784 117500 0.012718338 122500 0.010389396 127500 0.010001239 132500 0.007581451 137500 0.00851468 142500 0.007374985 147500 0.009629599 152500 0.006111409 157500 0.005756287 162500 0.005037783 167500 0.005095594 172500 0.00437709 177500 0.003798984 182500 0.002997894 187500 0.003138291 192500 0.002576702 197500 0.018970145 225000 0.023190321 300000 -------------------------------------------------------------------------------- /docs/.nojekyll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/docs/.nojekyll -------------------------------------------------------------------------------- /docs/CompMethodsLogo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/docs/CompMethodsLogo.png -------------------------------------------------------------------------------- /docs/CompMethodsLogo_gitfig.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/docs/CompMethodsLogo_gitfig.png -------------------------------------------------------------------------------- /docs/CompMethodsLogo_horizontal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/docs/CompMethodsLogo_horizontal.png -------------------------------------------------------------------------------- /docs/CompMethodsLogo_vertical.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/docs/CompMethodsLogo_vertical.png -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | # Instructions for files in CompMethods/docs 2 | The files in this directory `CompMethods/docs/` include images and all the files necessary for rendering the Jupyter Book documentation. One image [`CompMethodsLogo_gitfig.png`](docs/CompMethodsLogo_gitfig.png) is only used for the GitHub social preview image. GitHub suggests that this image should be 1280x640px for best display. The image we created [`CompMethodsLogo_horizontal.png`](docs/CompMethodsLogo_horizontal.png) is natively 759x267px. We do the following to resize the image. 3 | 4 | 1. Open the image in Adobe Photoshop: **File** > **Open** 5 | 2. Open the **Image Size** dialogue: 6 | 3. Adjust the canvas size: **Image** > **Canvas Size**. Because the 759x276px image is relatively wider than the optimal 1280x640px GitHub size, we first adjust the canvas size. We have to add a little width and some moderate height. So here adjust the canvas width to 760px and then increase the height to half that size 380px. 7 | 4. Adjust the image size: **Image** > **Image Size**. Now adjust the image size to the GitHub optimal 1280x640px. The dimesions will be correct and nothing will be stretched. 8 | 5. Save the image as [`CompMethodsLogo_gitfig.png`](docs/CompMethodsLogo_gitfig.png). 9 | 6. Upload the image [`CompMethodsLogo_gitfig.png`](docs/CompMethodsLogo_gitfig.png) as the GitHub social preview image by clicking on the [**Settings**](https://github.com/OpenSourceEcon/CompMethods/settings) button in the upper-right of the main page of the repository and uploading the formatted image [`CompMethodsLogo_gitfig.png`](docs/CompMethodsLogo_gitfig.png) in the **Social preview** section. 10 | -------------------------------------------------------------------------------- /docs/book/CompMethods_references.md: -------------------------------------------------------------------------------- 1 | # References 2 | 3 | ```{bibliography} CompMethods_references.bib 4 | :style: alpha 5 | ``` 6 | -------------------------------------------------------------------------------- /docs/book/_config.yml: -------------------------------------------------------------------------------- 1 | #################################################### 2 | # Computational Methods for Economists using Python, 3 | # Jupyter Book documentation settings 4 | #################################################### 5 | title : Computational Methods for Economists using Python 6 | author : Richard W. Evans 7 | copyright : '2023' 8 | logo : '..//CompMethodsLogo.png' 9 | 10 | #################################################### 11 | # Execution settings 12 | execute: 13 | execute_notebooks: force 14 | timeout: -1 15 | 16 | ####################################################################################### 17 | # Parse and render settings 18 | parse: 19 | myst_enable_extensions: # default extensions to enable in the myst parser. See https://myst-parser.readthedocs.io/en/latest/using/syntax-optional.html 20 | - amsmath 21 | - colon_fence 22 | # - deflist 23 | - dollarmath 24 | # - html_admonition 25 | # - html_image 26 | - linkify 27 | # - replacements 28 | # - smartquotes 29 | - substitution 30 | - tasklist 31 | - html_image 32 | myst_url_schemes: [mailto, http, https] # URI schemes that will be recognised as external URLs in Markdown links 33 | myst_dmath_double_inline: true # Allow display math ($$) within an inline context 34 | 35 | #################################################### 36 | # HTML-specific settings 37 | html: 38 | favicon : "..//favicon.ico" # A path to a favicon image 39 | use_edit_page_button : false # Whether to add an "edit this page" button to pages. If `true`, repository information in repository: must be filled in 40 | use_repository_button : true # Whether to add a link to your repository button 41 | use_issues_button : true # Whether to add an "open an issue" button 42 | use_multitoc_numbering : true # Continuous numbering across parts/chapters 43 | extra_navbar : Powered by Jupyter Book # Will be displayed underneath the left navbar. 44 | extra_footer : "" # Will be displayed underneath the footer. 45 | google_analytics_id : "" # A GA id that can be used to track book views. 46 | home_page_in_navbar : true # Whether to include your home page in the left Navigation Bar 47 | # baseurl : "" # The base URL where your book will be hosted. Used for creating image previews and social links. e.g.: https://mypage.com/mybook/ 48 | # analytics: 49 | # comments: 50 | # hypothesis : false 51 | # utterances : false 52 | # announcement : "" # A banner announcement at the top of the site. 53 | 54 | ####################################################################################### 55 | # LaTeX and BibTex settings 56 | latex: 57 | latex_engine : pdflatex # one of 'pdflatex', 'xelatex' (recommended for unicode), 'luatex', 'platex', 'uplatex' 58 | use_jupyterbook_latex : true # use sphinx-jupyterbook-latex for pdf builds as default 59 | 60 | bibtex_bibfiles: 61 | - CompMethods_references.bib 62 | #################################################### 63 | # Launch button settings 64 | launch_buttons: 65 | notebook_interface : 'classic' # The interface interactive links will activate ["classic", "jupyterlab"] 66 | # binderhub_url : https://mybinder.org # The URL of the BinderHub (e.g., https://mybinder.org) 67 | # jupyterhub_url : "" # The URL of the JupyterHub (e.g., https://datahub.berkeley.edu) 68 | # thebelab : false # Add a thebelab button to pages (requires the repository to run on Binder) 69 | colab_url: "https://colab.research.google.com" # The URL of Google Colab 70 | 71 | ####################################################################################### 72 | # FiscalSim-US repository settings 73 | repository: 74 | url: https://github.com/OpenSourceEcon/CompMethods 75 | branch: main 76 | path_to_book: "docs/book" 77 | 78 | ####################################################################################### 79 | # Advanced Sphinx settings 80 | sphinx: 81 | config: # key-value pairs to directly over-ride the Sphinx configuration 82 | bibtex_reference_style: author_year 83 | mathjax_path: https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js 84 | html_js_files: 85 | - https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js 86 | # html_theme: furo 87 | pygments_style: default 88 | extra_extensions: 89 | - "sphinx.ext.autodoc" 90 | - "sphinxarg.ext" 91 | - "sphinx.ext.viewcode" 92 | - "sphinx.ext.napoleon" 93 | - "sphinx.ext.mathjax" 94 | - "alabaster" 95 | - "sphinx_exercise" 96 | - "sphinx_proof" 97 | -------------------------------------------------------------------------------- /docs/book/_static/custom.css: -------------------------------------------------------------------------------- 1 | /* docs/book/_static/custom.css */ 2 | 3 | :root { 4 | --background-color: rgba(55, 253, 20, 0.158); 5 | --border-color: #9cfd14bb; 6 | } 7 | 8 | div.green { 9 | background-color: var(--background-color); 10 | border-color: var(--border-color); 11 | } 12 | 13 | div.green p.admonition-title { 14 | background-color: var(--background-color); 15 | } 16 | -------------------------------------------------------------------------------- /docs/book/_toc.yml: -------------------------------------------------------------------------------- 1 | format: jb-book 2 | root: index 3 | parts: 4 | - caption: Contributor Guide 5 | chapters: 6 | - file: contrib/contributing 7 | - caption: Coding in Python 8 | numbered: True 9 | chapters: 10 | - file: python/intro 11 | - file: python/StandardLibrary 12 | - file: python/ExceptionsIO 13 | - file: python/OOP 14 | - file: python/NumPy 15 | - file: python/Pandas 16 | - file: python/Matplotlib 17 | - file: python/SciPy 18 | - file: python/DocStrings 19 | - file: python/UnitTesting 20 | - caption: Git and GitHub 21 | numbered: True 22 | chapters: 23 | - file: git/intro 24 | - caption: Basic Empirical Methods 25 | numbered: True 26 | chapters: 27 | - file: basic_empirics/BasicEmpirMethods 28 | - file: basic_empirics/LogisticReg 29 | - caption: Basic Machine Learning 30 | numbered: True 31 | chapters: 32 | - file: basic_ml/ml_intro 33 | - caption: Neural Nets and Deep Learning 34 | numbered: True 35 | chapters: 36 | - file: deep_learn/intro 37 | - caption: Structural Estimation 38 | numbered: True 39 | chapters: 40 | - file: struct_est/intro 41 | - file: struct_est/MLE 42 | - file: struct_est/GMM 43 | - file: struct_est/SMM 44 | - file: struct_est/paper 45 | - caption: Appendix 46 | chapters: 47 | - file: appendix/glossary 48 | - file: appendix/appendix 49 | - caption: References 50 | chapters: 51 | - file: CompMethods_references 52 | -------------------------------------------------------------------------------- /docs/book/appendix/appendix.md: -------------------------------------------------------------------------------- 1 | (Chap_Appendix)= 2 | # Appendix 3 | 4 | Put Appendix intro here. 5 | 6 | (SecAppendixTruncNormal)= 7 | ## Truncated normal distribution 8 | 9 | The truncated normal distribution with parameters $\mu$ and $\sigma$ and lower-bound cutoff $c_{lb}$ and upper-bound cutoff $c_{ub}$ is simply the normal distribution of values of the random variable $x$ defined only on the interval $x\in[c_{lb}, c_{ub}]$ rather than on the full real line. And the probability distribution function values are upweighted by the probability (less than one) under the normal distribution on the interval $[c_{lb}, c_{ub}]$. 10 | ```{math} 11 | :label: EqAppendix_TruncNorm 12 | \text{truncated normal:}\quad &f(x|\mu,\sigma,c_{lb},c_{ub}) = \frac{\phi(x|\mu,\sigma)}{\Phi(c_{ub}|\mu,\sigma) - \Phi(c_{ub}|\mu,\sigma)} \\ 13 | &\text{where}\quad \phi(x|\mu,\sigma) \equiv \frac{1}{\sqrt{2\pi\sigma^2}}e^{-\frac{x - \mu}{2\sigma^2}} \\ 14 | &\text{and}\quad \Phi(x|\mu,\sigma) \equiv \int_{-\infty}^x\phi(x|\mu,\sigma) dx 15 | ``` 16 | 17 | The function $\phi(x|\mu,\sigma)$ is the probability distribution function of the normal distribution with mean $\mu$ and variance $\sigma^2$. And the function $\Phi(x|\mu,\sigma)$ is the cummulative distribution function of the normal distribution with mean $\mu$ and variance $\sigma^2$. 18 | 19 | 20 | (SecAppendixFootnotes)= 21 | ## Footnotes 22 | 23 | The footnotes from this appendix. 24 | -------------------------------------------------------------------------------- /docs/book/basic_ml/ml_intro.md: -------------------------------------------------------------------------------- 1 | (Chap_BasicMLintro)= 2 | # Basic Machine Learning 3 | 4 | Put basic machine learning intro here. 5 | 6 | Define regression model versus classification model. Define parametric model versus nonparametric model. Define supervised learning versus unsupervised learning. 7 | 8 | Introduce the paradigm of cross-validation. 9 | 10 | The definitions of machine learning, statistical learning, and artificial intelligence overlap in most cases. And in some contexts they are indistinguishable. 11 | 12 | Machine learning, statistical learning, and artificial intelligence is mostly focused on predictive models $\hat{y}=f(x|\theta)$ and tuning or estimating the parameters $\theta$ to minimize some definition of total error in the predictions for $\hat{y}$. 13 | * Highly nonlinear models 14 | * Cross-validation 15 | * Exotic loss functions 16 | * Super robust minimizers (variants of stochastic gradient descent) 17 | 18 | Machine learning could have an equally appropriate and nondescriptive name of nonlinear regression modeling. On predictive accuracy, machine learning models outperform structural models and top regression models. However, this accuracy often comes at the cost of interpretability. The estimated parameters in structural models and regression models often have clear interpretations. On the other hand, it is nearly impossible to make a robust claim about the effect of an explanatory variable on a dependent variable in a neural net model. 19 | 20 | Recent advances by Athey and others have re-established the elements of interpretation, marginal effects, and causal inference to machine learning models. [include citations here.] 21 | 22 | 23 | (SecBasicMLintroFootnotes)= 24 | ## Footnotes 25 | 26 | The footnotes from this chapter. 27 | -------------------------------------------------------------------------------- /docs/book/conf.py: -------------------------------------------------------------------------------- 1 | # conf.py 2 | 3 | html_static_path = ["./_static"] 4 | 5 | # CSS files 6 | html_css_files = [ 7 | "custom.css", 8 | ] 9 | 10 | # Get rid of transitions error/warning 11 | myst_footnote_transition = False 12 | -------------------------------------------------------------------------------- /docs/book/contrib/contributing.md: -------------------------------------------------------------------------------- 1 | (Chap_Contrib)= 2 | # Contributor Guide 3 | 4 | This chapter details how to contribute to the *Computational Methods for Economists using Python* book and associated repository. The CompMethods project follows the [GitHub workflow](https://guides.github.com/introduction/flow/) and [semantic versioning protocol](http://semver.org/). 5 | 6 | 7 | ## Create an Issue 8 | 9 | If you have a suggestion, correction, or addition you want to contribute to the CompMethods project and content, a good first approach is to file an Issue in the repository by going to the [Issues page](https://github.com/OpenSourceEcon/CompMethods/issues) and selecting the green "[New issue](https://github.com/OpenSourceEcon/CompMethods/issues/new)" button. For a productive new issue, please include the following. 10 | * Clear and concise issue title that directly references the key point in your issue 11 | * Clear and concise description of your question, problem, or error 12 | * Error traceback message output or other terminal output 13 | * Include a [minimal reproducible example](https://en.wikipedia.org/wiki/Minimal_reproducible_example) 14 | 15 | 16 | ## Pull requests 17 | 18 | This project follows the [GitHub Flow](https://guides.github.com/introduction/flow/). All code contributions are submitted via a [pull request](https://github.com/OpenSourceEcon/CompMethods/pulls) towards the `main` branch. Opening a Pull Request means you are submitting all of the lines of code you have changed in a branch of your fork of this repository that you want to be considered to be merged into the repository. Once a pull request is submitted, project maintainers will review your submission and may ask for changes and clarifications via the pull request message thread. Once the reviewers are satisfied with the submission, they will merge it into the repository and those changes will become part of the project. 19 | 20 | ### Automatic testing 21 | 22 | This project uses GitHub Actions to run automatic tests to make sure that the documentation builds, that the code runs correctly, and that the code is formatted correctly. In your pull requests, you should signify that you have run these tests locally on your machine using the `compmethods-dev` conda environment and successfully running the `make documentation`, `make test`, and `make format` commands. These tests will run automatically in the cloud on every commit to every pull request, but it is helpful for you to successfully run those tests locally on your machine. 23 | 24 | 25 | ### Peer reviews 26 | 27 | All pull requests must be reviewed by someone else than their original author, with few exceptions of pull requests from the main model maintainers. To help reviewers, make sure to add to your PR a **clear text explanation** of your changes. In case of changes that break past functionality and connections, you **must** give details about what features were deprecated. You must also provide guidelines to help users adapt their code to be compatible with the new version of the package. 28 | 29 | ## Project version tracking 30 | 31 | This project follows the [semantic versioning protocol](http://semver.org/). Any change impacts the version number, and the version number conveys API compatibility information **only**. 32 | 33 | Every pull request submitted to the main branch of the repository should update the `CHANGELOG.md` file as well as update the version number of the project in `setup.py`. 34 | 35 | ### Patch bump (3rd digit update) 36 | 37 | - Typographical and stylistic updates. Small code and data updates. 38 | - Update the third digit of the version number. Ex: Version number would move from 0.0.0 to 0.0.1. 39 | 40 | ### Minor bump 41 | 42 | - Adding a new section, major data, or majore code example to the Jupyter Book 43 | - Update the second digit of the version number. Ex: Version number would move from 0.0.0 to 0.1.0. 44 | 45 | ### Major bump 46 | 47 | - Major update, refactor, or compatibility change. 48 | - Update the first digit of the version number. Ex: Version number would move from 0.0.0 to 1.0.0. 49 | -------------------------------------------------------------------------------- /docs/book/deep_learn/intro.md: -------------------------------------------------------------------------------- 1 | (Chap_DeepLearnIntro)= 2 | # Neural Nets and Deep Learning 3 | 4 | Put neural nets and deep learning intro here. 5 | 6 | 7 | (SecDeepLearnIntroFootnotes)= 8 | ## Footnotes 9 | 10 | 11 | -------------------------------------------------------------------------------- /docs/book/images/Git/GitFlowDiag.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/docs/book/images/Git/GitFlowDiag.png -------------------------------------------------------------------------------- /docs/book/images/SciPy/root_examp1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/docs/book/images/SciPy/root_examp1.png -------------------------------------------------------------------------------- /docs/book/images/icon_GitHub.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/docs/book/images/icon_GitHub.png -------------------------------------------------------------------------------- /docs/book/images/icon_background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/docs/book/images/icon_background.png -------------------------------------------------------------------------------- /docs/book/images/icon_download.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/docs/book/images/icon_download.png -------------------------------------------------------------------------------- /docs/book/images/icon_fullscreen.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/docs/book/images/icon_fullscreen.png -------------------------------------------------------------------------------- /docs/book/images/icon_search.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/docs/book/images/icon_search.png -------------------------------------------------------------------------------- /docs/book/index.md: -------------------------------------------------------------------------------- 1 | # Computational Methods for Economists using Python 2 | 3 | | | | 4 | | --- | --- | 5 | | Org | [![OSE Lab cataloged](https://img.shields.io/badge/OSE%20Lab-catalogued-critical)](https://github.com/OpenSourceEcon) [![OS License: AGPL-3.0](https://img.shields.io/badge/OS%20License-AGPL%203.0-yellow)](https://github.com/OpenSourceEcon/CompMethods/blob/main/LICENSE) [![Jupyter Book Badge](https://jupyterbook.org/badge.svg)](https://opensourceecon.github.io/CompMethods/) | 6 | | Package | [![Python 3.10](https://img.shields.io/badge/python-3.10-blue.svg)](https://www.python.org/downloads/release/python-31013/) [![Python 3.11](https://img.shields.io/badge/python-3.11-blue.svg)](https://www.python.org/downloads/release/python-3115/) | 7 | | Testing | ![example event parameter](https://github.com/OpenSourceEcon/CompMethods/actions/workflows/build_and_test.yml/badge.svg?branch=main) ![example event parameter](https://github.com/OpenSourceEcon/CompMethods/actions/workflows/deploy_docs.yml/badge.svg?branch=main) ![example event parameter](https://github.com/OpenSourceEcon/CompMethods/actions/workflows/check_format.yml/badge.svg?branch=main) [![Codecov](https://codecov.io/gh/OpenSourceEcon/CompMethods/branch/main/graph/badge.svg)](https://codecov.io/gh/OpenSourceEcon/compmethods) | 8 | 9 | This online book site contains open access tutorial materials and exercises for learning and using modern computational methods used by economists and data scientists. These materials have been developed by [Richard W. Evans](https://sites.google.com/site/rickecon) since 2008 primarily through the following endeavors: 10 | * (2008-2016) Assistant Professor, Department of Economics, Brigham Young University. Taught undergraduate courses in macroeconomics, international finance, advanced macroeconomics, computational methods. 11 | * (2012-2016) Co-founder and co-director of the BYU Macroeconomics and Computational Laboratory. 12 | * (2013-2016) Co-PI, National Science Foundation Grant for original development of Applied and Computational Math Emphasis (ACME) curriculum at Brigham Young University. 13 | * (2013-present) National advisory board member for the Applied and Computational Math Emphasis (ACME), Brigham Young University. 14 | * (2014-2018) Economist, Open Source Policy Center, American Enterprise Institute. 15 | * (2016-present) Founder and Director, Open Source Economics Laboratory. 16 | * (2016-2019) Fellow, Becker Friedman Institute, University of Chicago. 17 | * (2016-2020) Senior Lecturer and Associate Director, Masters in Computational Social Science, University of Chicago. Taught graduate students data science, computational methods, structural estimation, overlapping generations models. 18 | * (2016-present) President, Open Research Group, Inc. 19 | * (2022-present) Senior Research Fellow and Director of Open Policy, Center for Growth and Opportunity at Utah State University. 20 | 21 | The core maintainer of this project is the following. However, some of the chapters have been jointly developed with coauthors as noted at the top of some chapters. 22 | * [**Richard W. Evans**](https://sites.google.com/site/rickecon), Senior Research Fellow and Director of Open Policy, Center for Growth and Opportunity at Utah State University; President and Co-founder, Open Research Group, Inc. (GitHub handle: [@rickecon](https://github.com/rickecon)) 23 | 24 | We welcome collaboration on the maintenance and improvement of this tutorial. If you have changes you would like to see or errors that you find, please open [an issue](https://github.com/OpenSourceEcon/CompMethods/issues) in the GitHub repository or submit a [pull request](https://github.com/OpenSourceEcon/CompMethods/pulls). More details on how to collaborate with this project are the {ref}`Chap_Contrib` chapter. 25 | 26 | 27 | ## Tutorial site functionality 28 | This site was created using the [Executable Books](https://executablebooks.org/) [Jupyter Book](https://jupyterbook.org/) platform. All of the content for this tutorial material is publicly accessible, available, and version controlled in the GitHub repository (https://github.com/OpenSourceEcon/CompMethods) associated with this book. Some of the functionality of this tutorial site includes the following: 29 | * **Navigate** through the chapters and sections of the tutorial materials using the chapter table of contents on the left side of the site, and navigate through subsections of each chapter using the subsection table of contents on the right side of each page. 30 | * Click on the GitHub icon in the upper-right of each page to go to the **GitHub repository** or open and issue in the repository. 31 | * **Download** each page as a markdown file `.md` or a PDF file `.pdf` by clicking on the download icon in the upper-right of each page. 32 | * Toggle between a desktop window or **full-screen mode** by clicking on the full screen icon in the upper-right of each page. 33 | * Change the **background** from light to dark to automatic using the background brightness icon in the upper-right of each page. 34 | * **Search** for terms in the training materials using by clicking on the search icon in the upper-fight of each page and entering your search terms. 35 | 36 | 37 | ## Associated repository components 38 | Code related to labs and exercises in the online book are posted in the [`./code/`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code) directory of the book's GitHub repository. The `code` directory has subdirectories that are organized by chapter name. 39 | 40 | Data related to labs and exercises in the online book are posted in the [`./data/`](https://github.com/OpenSourceEcon/CompMethods/tree/main/data) directory of the book's GitHub repository. The `data` directory has subdirectories that are organized by chapter name. 41 | 42 | Images related to labs and exercises in the online book are posted in the [`./images/`](https://github.com/OpenSourceEcon/CompMethods/tree/main/images) directory of the book's GitHub repository. The `images` directory has subdirectories that are organized by chapter name. 43 | 44 | 45 | ## Citing this book 46 | Please use the following citation form for this book. 47 | 48 | General citation to the book: 49 | * Evans, Richard W., *Computational Methods for Economists using Python*, Open access Jupyter Book, v#.#.#, 2023, https://opensourceecon.github.io/CompMethods. 50 | 51 | Citation to a chapter in the book only authored by Evans: 52 | * Evans, Richard W., "[insert chapter name]", in *Computational Methods for Economists using Python*, Open access Jupyter Book, v#.#.#, 2023, https://opensourceecon.github.io/CompMethods + [chapter path]. 53 | 54 | Citation to a chapter in the book only authored by multiple authors: 55 | * DeBacker, Jason and Richard W. Evans, "[insert chapter name]", in *Computational Methods for Economists using Python*, Open access Jupyter Book, v#.#.#, 2023, https://opensourceecon.github.io/CompMethods + [chapter path]. 56 | -------------------------------------------------------------------------------- /docs/book/python/ExceptionsIO.md: -------------------------------------------------------------------------------- 1 | (Chap_ExceptIO)= 2 | # Exception Handling and File Input/Output 3 | 4 | This chapter was coauthored by Jason DeBacker and Richard W. Evans. 5 | 6 | Python stops the computation process when it encounters an error. Sometimes you want to describe certain errors with descriptive error messages. And sometimes you want your code to move past errors while saving them and including descriptive error messages. Other times, you want to ensure that no errors occur and that your program stops and informs you in the case of an error. 7 | 8 | Python's error handling, assertion functionality, traceback capability, and type hinting are powerful methods to make sure your code does what you expect it to do, breaks when you expect it to break, and moves past issues when you don't want the computation to stop. 9 | 10 | The iframe below contains a PDF of the BYU ACME open-access lab entitled, "Exceptions and File Input/Output". You can either scroll through the lab on this page using the iframe window, or you can download the PDF for use on your computer. See {cite}`BYUACME_ExceptIO`. {numref}`ExerExceptionIO` below has you work through the problems in this BYU ACME lab. The Python file ([`exceptions_fileIO.py`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/Exceptions_FileIO/exceptions_filIO.py)) and associated text files (`.txt`) associated with this lab are stored in the [`./code/Exceptions_FileIO/`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/Exceptions_FileIO) directory. 11 | 12 |
13 | 19 |
20 | 21 | 22 | (SecExceptIOExercises)= 23 | ## Exercises 24 | 25 | ```{exercise-start} 26 | :label: ExerExceptionIO 27 | :class: green 28 | ``` 29 | Read the BYU ACME "[Exceptions and file input/output](https://drive.google.com/file/d/1gAam1i1Gy0YgULT92ul72DUqRCb4q2fA/view?usp=sharing)" lab and complete Problems 1 through 4 in the lab. {cite}`BYUACME_ExceptIO` 30 | ```{exercise-end} 31 | ``` 32 | -------------------------------------------------------------------------------- /docs/book/python/Matplotlib.md: -------------------------------------------------------------------------------- 1 | (Chap_Matplotlib)= 2 | # Matplotlib 3 | 4 | This chapter was coauthored by Jason DeBacker and Richard W. Evans. 5 | 6 | [Matplotlib](https://matplotlib.org) is Python's most widely used and most basic visualization package.[^Matplotlib1] Some of the other most popular Python visualization packages [Bokeh](http://bokeh.org/), [Plotly](https://plotly.com/), and [Seaborn](https://seaborn.pydata.org/). Of these, Matplotlib is the most general for static images and is what is used on `OG-Core`. Once you have a general idea of how to create plots in Python, that knowlege will generalize (to varying degrees) to the other plotting packages. 7 | 8 | The iframe below contains a PDF of the BYU ACME open-access lab entitled, "[Introduction to Matplotlib](https://drive.google.com/file/d/12dnf8tjXBExoQf6W3J5_b52AN27GoBTV/view?usp=sharing)". You can either scroll through the lab on this page using the iframe window, or you can download the PDF for use on your computer. See {cite}`BYUACME_Matplotlib1`. {numref}`ExerMatplot-acme1` below has you work through the problems in this BYU ACME lab. A Python file template ([`matplotlib_intro.py`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/Matplotlib1/matplotlib_intro.py)) and a data file ([`FARS.npy`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/Matplotlib1/FARS.npy)) used in the lab are stored in the [`./code/Matplotlib1/`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/Matplotlib1) directory. 9 | 10 |
11 | 17 |
18 | 19 | The iframe below contains a PDF of the BYU ACME open-access lab entitled, "[Pandas 2: Plotting](https://drive.google.com/file/d/1grhP5AcxR9uzvTHSmM4Q4kABM0XENH8r/view?usp=sharing)". In spite of having "Pandas" in the title, we include this lab here in this Matplotlib chapter because all of the plotting uses the Matplotlib package. You can either scroll through the lab on this page using the iframe window, or you can download the PDF for use on your computer. See {cite}`BYUACME_Matplotlib2`. {numref}`ExerMatplot-acme2` below has you work through the problems in this BYU ACME lab. A Jupyter notebook file template ([`matplotlib2.ipynb`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/Matplotlib2/matplotlib2.ipynb)) used in the lab is stored in the [`./code/Matplotlib2/`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/Matplotlib2) directory. The [`budget.csv`](https://github.com/OpenSourceEcon/CompMethods/tree/main/data/Pandas1/budget.csv) and [`crime_data.csv`](https://github.com/OpenSourceEcon/CompMethods/tree/main/data/Pandas1/crime_data.csv) data files are stored in the [`./data/Pandas1`](https://github.com/OpenSourceEcon/CompMethods/tree/main/data/Pandas1) directory, which were used in the "[Pandas 1: Introduction](https://drive.google.com/file/d/1t5fjjQXBSIYekZUZIDRvMQOcfCpy8edh/view?usp=sharing)" lab. And the other data file used in this lab [`college.csv`](https://github.com/OpenSourceEcon/CompMethods/tree/main/data/Pandas3/college.csv) is stored in the [`./data/Pandas3`](https://github.com/OpenSourceEcon/CompMethods/tree/main/data/Pandas3) directory, which was used in the "[Pandas 3: Grouping](https://drive.google.com/file/d/13DoapcC2whPxSzQQCRaOKv6jow4AkeuZ/view?usp=sharing)" lab. 20 | 21 |
22 | 28 |
29 | 30 | 31 | (SecMatplotlibAnim3D)= 32 | ## (Optional): Animations and 3D 33 | 34 | This section with its accompanying BYU ACME lab and {numref}`ExerMatplot-acme3` is optional because these plotting skills are used less often and because other plotting packages do a better job of visualization dynamics. That said, this lab is a good one. And the 3D plotting in Matplotlib is fairly good. 35 | 36 | The iframe below contains a PDF of the BYU ACME open-access lab entitled, "[Animations and 3D Plotting in Matplotlib](https://drive.google.com/file/d/19y4Uhe4uckSx83duWyELrUz0K-tiYGFc/view?usp=sharing)". You can either scroll through the lab on this page using the iframe window, or you can download the PDF for use on your computer. See {cite}`BYUACME_Matplotlib3`. Optional {numref}`ExerMatplot-acme3` below has you work through the problems in this BYU ACME lab. A Jupyter notebook file template ([`animation.ipynb`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/Matplotlib3/animation.ipynb)) used in the lab is stored in the [`./code/Matplotlib3/`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/Matplotlib3) directory. And two data files used in the lab are stored in the [`./data/Matplotlib3`](https://github.com/OpenSourceEcon/CompMethods/tree/main/data/Matplotlib3) directory. 37 | 38 |
39 | 45 |
46 | 47 | 48 | (SecMatplotlibExercises)= 49 | ## Exercises 50 | 51 | ```{exercise-start} 52 | :label: ExerMatplot-acme1 53 | :class: green 54 | ``` 55 | Read the BYU ACME "[Introduction to Matplotlib](https://drive.google.com/file/d/12dnf8tjXBExoQf6W3J5_b52AN27GoBTV/view?usp=sharing)" lab and complete Problems 1 through 6 in the lab. {cite}`BYUACME_Matplotlib1` 56 | ```{exercise-end} 57 | ``` 58 | 59 | ```{exercise-start} 60 | :label: ExerMatplot-acme2 61 | :class: green 62 | ``` 63 | Read the BYU ACME "[Pandas 2: Plotting](https://drive.google.com/file/d/1grhP5AcxR9uzvTHSmM4Q4kABM0XENH8r/view?usp=sharing)" lab and complete Problems 1 through 4 in the lab. {cite}`BYUACME_Matplotlib2` 64 | ```{exercise-end} 65 | ``` 66 | 67 | ```{exercise-start} OPTIONAL: Animations nad 3D 68 | :label: ExerMatplot-acme3 69 | :class: green 70 | ``` 71 | Read the BYU ACME "[Animations and 3D Plotting in Matplotlib](https://drive.google.com/file/d/19y4Uhe4uckSx83duWyELrUz0K-tiYGFc/view?usp=sharing)" lab and complete Problems 1 through 5 in the lab. {cite}`BYUACME_Matplotlib3` 72 | ```{exercise-end} 73 | ``` 74 | 75 | 76 | ```{exercise-start} 77 | :label: ExerMatplot-bar 78 | :class: green 79 | ``` 80 | Using the country GDP DataFrame you created in Exercise {numref}`ExerPandas-make_df`, collapse these data to find mean GDP per capita by country. Create a bar plot that shows the means for each of the four countries. 81 | ```{exercise-end} 82 | ``` 83 | 84 | ```{exercise-start} 85 | :label: ExerMatplot-grouped_bar 86 | :class: green 87 | ``` 88 | Using same DataFrame as above, create a grouped bar plot that represents the full DataFrame and shows GDP per capita for each country and year. Group the bar plot so that there is a grouping for each decade and within each group, all four countries are represented. 89 | ```{exercise-end} 90 | ``` 91 | 92 | (SecMatplotlibFootnotes)= 93 | ## Footnotes 94 | 95 | The footnotes from this chapter. 96 | 97 | [^Matplotlib1]: Matplotlib's website is https://matplotlib.org. 98 | -------------------------------------------------------------------------------- /docs/book/python/NumPy.md: -------------------------------------------------------------------------------- 1 | (Chap_Numpy)= 2 | # NumPy 3 | 4 | This chapter was coauthored by Jason DeBacker and Richard W. Evans. 5 | 6 | NumPy is Python's fundamantal numerical package (the name stands for "numerical Python"), and is at the basis of most computation using Python.[^NumPy] Our discussion of Python's NumPy package starts with Travis Oliphant, who was the primary creator of the NumPy package, a founding contributor to Python's SciPy package (covered in the {ref}`Chap_SciPy` chapter), founder of [Anaconda, Inc.](https://www.anaconda.com/) that maintains the most popular distribution of Python, and a co-founder of the [NumFOCUS](https://numfocus.org/) non-profit that fiscally supports some of the primary package projects in Python.[^Oliphant] 7 | 8 | Oliphant was a mathematics and electrical engineering student who came up through his masters degree using MATLAB with a focus primarily on signal processing. While working on a PhD, he needed to create custom code that could do signal processing operations that had never been done before. These operations required combinations of mathematical operations. Oliphant liked the ideas of network and collaboration in the open source software community, and Python was a language that felt intuitive and comfortable to him. However, Python had no established numerical matrix operations libraries. Oliphant created the NumPy package to be that numerical engine based on linear algebra array operations. 9 | 10 | The fundamental object of the NumPy package is the NumPy array [`numpy.array`](https://numpy.org/doc/stable/reference/generated/numpy.array.html). Python's native objects---such as lists, tuples, and dictionaries---can hold numbers and perform operations on those numbers. But the NumPy array allows for storing high-dimensional arrays of numbers on which linear algebra and tensor functions can be operated. These linear algebra operations are more effecient than working with lists and tuples, and they form the foundation of modern optimization and machine learning. Learning to use Python's NumPy package is an essential skill for many numerical computations and other operations. 11 | 12 | The iframe below contains a PDF of the BYU ACME open-access lab entitled, "Introduction to NumPy". You can either scroll through the lab on this page using the iframe window, or you can download the PDF for use on your computer. See {cite}`BYUACME_NumPy1`. {numref}`ExerNumPy-acme1` below has you work through the problems in this BYU ACME lab. A Python file template ([`numpy_intro.py`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/NumPyIntro/numpy_intro.py)) and a matrix data file ([`grid.npy`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/NumPyIntro/grid.npy)) used in the lab are stored in the [`./code/NumPyIntro/`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/NumPyIntro) directory. 13 | 14 |
15 | 21 |
22 | 23 | The following iframe contains a PDF of the BYU ACME open-access lab entitled, "Advanced NumPy", which contains content and exercises that build off of the previous BYU ACME NumPy lab. You can either scroll through the lab on this page using the iframe window, or you can download the PDF for use on your computer. See {cite}`BYUACME_NumPy2`. {numref}`ExerNumPy-acme2` below has you work through the problems in this BYU ACME lab. A Python file template ([`advanced_numpy.py`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/AdvancedNumPy/_advanced_numpy.py)) used in the lab are stored in the [`./code/AdvancedNumPy/`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/AdvancedNumPy) directory. 24 | 25 |
26 | 32 |
33 | 34 | 35 | (SecNumPyExtensions)= 36 | ## Extensions and future paths 37 | 38 | One of the drawbacks to the degree to which NumPy arrays are fundamental to Python's numerical computing is that the format of those arrays is a requirement in Python's most highly used scientific computing and machine learning packages ({ref}`Chap_SciPy` and scikit-learn). However, advances in hardware, large data methods, and optimization algorithms now take much more advantage of parallel computing algorithms, hybrid architectures across multiple traditional processors and GPU's. All of these innovations have been difficult to incorporate into Python's scientific computing stack because NumPy arrays have been difficult to make flexible to these architectures. 39 | 40 | Below are three areas that have been working to make Python better on these dimentions. 41 | * Dask arrays 42 | * QuantSight development and support of array API's in SciPy and in scikit-learn. See here for the [scikit-learn blog post](https://labs.quansight.org/blog/array-api-support-scikit-learn). And see here for the [SciPy blog post](https://labs.quansight.org/blog/scipy-array-api). 43 | * Modular's development of the Mojo programming language. 44 | 45 | 46 | (SecNumPyExercises)= 47 | ## Exercises 48 | 49 | ```{exercise-start} 50 | :label: ExerNumPy-acme1 51 | :class: green 52 | ``` 53 | Read the BYU ACME "[Introduction to NumPy](https://drive.google.com/file/d/1Hj3ok81gJAxcUTHh_8BrxX-B4belupPN/view?usp=sharing)" lab and complete Problems 1 through 7 in the lab. {cite}`BYUACME_NumPy1` 54 | ```{exercise-end} 55 | ``` 56 | 57 | ```{exercise-start} 58 | :label: ExerNumPy-acme2 59 | :class: green 60 | ``` 61 | Read the BYU ACME "[Advanced NumPy](https://drive.google.com/file/d/15KxliSp0C_mLf7TrLQbnC0wO4YaK7ePi/view?usp=sharing)" lab and complete Problems 1 through 7 in the lab. {cite}`BYUACME_NumPy2` 62 | ```{exercise-end} 63 | ``` 64 | 65 | ```{exercise-start} 66 | :label: ExerNumpy-array 67 | :class: green 68 | ``` 69 | Create a Numpy array `b` (defined this as the savings of 2 agents (the rows) over 5 periods (the columns)): 70 | \begin{equation*} 71 | b= \begin{bmatrix} 72 | 1.1 & 2.2 & 3.0 & 2.0 & 1.0 \\ 73 | 3.3 & 4.4 & 5.0 & 3.7 & 2.0 74 | \end{bmatrix} 75 | \end{equation*} 76 | Use the `shape` method of NumPy arrays to print the shape of this matrix. Use array slicing to print the first row of `b`, which represents the lifecycle savings decisions of the first agent (i.e., the amount they choose to save in each of their 5 periods of life). Use array slicing to print the second column of `b`, which is the savings of both agents when they are in their second period of life. Finally, use array slicing to print the first two rows and the last three columns of `b` (i.e., the savings of both agents from middle age onwards). 77 | ```{exercise-end} 78 | ``` 79 | 80 | ```{exercise-start} 81 | :label: ExerNumpy-dotproduct 82 | :class: green 83 | ``` 84 | Now let's think about the matrix `b` as representing not two individual agents, but two types of agents who each live for five periods. In this way, we will interpret the values in `b` as the total savings of different cohorts of these two types of agents who are all living together at a point in time. Now, define a matrix `Omega`: 85 | \begin{equation*} 86 | \Omega= 87 | \begin{bmatrix} 88 | 0.05 & 0.05 & 0.08 & 0.06 & 0.2 \\ 89 | 0.12 & 0.16 & 0.03 & 0.2 & 0.05 90 | \end{bmatrix} 91 | \end{equation*} 92 | `Omega` represents the fraction of agents in the economy of each type/cohort (Note that the elements of `Omega` sum to 1). Use matrix multiplication to find `B`, which is the dot product of `b` and the transpose of `Omega`. 93 | \begin{equation*} 94 | B = b\Omega^T 95 | \end{equation*} 96 | Print your matrix `B`. What is its shape? What does `B` represent? 97 | ```{exercise-end} 98 | ``` 99 | 100 | ```{exercise-start} 101 | :label: ExerNumpy-mult 102 | :class: green 103 | ``` 104 | Multiply element-wise (Hadamard product) the matrix `b` from {numref}`ExerNumpy-array` by the matrix `Omega` from {numref}`ExerNumpy-dotproduct`. Use the `numpy.array.sum()` method on the resulting matrix, with the appropriate `axis` argument in the parentheses to find the total savings of each cohort. 105 | ```{exercise-end} 106 | ``` 107 | 108 | ```{exercise-start} 109 | :label: ExerNumpy-zeros 110 | :class: green 111 | ``` 112 | In one line, create a matrix of zeros that is the same size as `b` from {numref}`ExerNumpy-array`. 113 | ```{exercise-end} 114 | ``` 115 | 116 | ```{exercise-start} 117 | :label: ExerNumpy-where 118 | :class: green 119 | ``` 120 | Use `numpy.where` to return the elements of `b` from {numref}`ExerNumpy-array` that are greater than 2.0 and zero elsewhere. 121 | ```{exercise-end} 122 | ``` 123 | 124 | ```{exercise-start} 125 | :label: ExerNumpy-stack 126 | :class: green 127 | ``` 128 | Now suppose a third type of agent. This agent has savings $b_3 = \left[4.1, 5.1, 7.1, 4.5, 0.9\right]$. Use `numpy.vstack` to stack `b` from {numref}`ExerNumpy-array` on top of `b_3` to create a new $3\times 5$ matrix `b_new`. 129 | ```{exercise-end} 130 | ``` 131 | 132 | (SecNumPyFootnotes)= 133 | ## Footnotes 134 | 135 | The footnotes from this chapter. 136 | 137 | [^NumPy]: The website for NumPy is https://numpy.org. 138 | 139 | [^Oliphant]: Travis Oliphant has a [Wikipedia page](https://en.wikipedia.org/wiki/Travis_Oliphant) {cite}`OliphantWiki`. We highly recommend [Oliphant's interview](https://youtu.be/gFEE3w7F0ww?si=XKcRlcw7FXkA9oxB) on the Lex Fridman Podcast from September 22, 2021 {cite}`Fridman:2021`. 140 | -------------------------------------------------------------------------------- /docs/book/python/OOP.md: -------------------------------------------------------------------------------- 1 | (Chap_OOP)= 2 | # Object Oriented Programming 3 | 4 | This chapter was coauthored by Jason DeBacker and Richard W. Evans. 5 | 6 | Python is literally a programming language built on objects. Objects are instances of classes. And classes are definitions of objects with their corresponding methods and attributes. Objects are a powerful way to group functionality and attributes in a class that has a limited and common set of characteristics. 7 | 8 | An analogy is how life forms are classified by [taxonomic rank](https://en.wikipedia.org/wiki/Taxonomic_rank) going from most general to most specific: domain, kingdom, phylum, class, order, family, genus, and species {cite}`WikiTaxonomicRank`. If you have a model of all the different types of cats, you would probably care about the taxonomic rank *family* of *felidae* or cats. If you were interested in modeling all the different types of mammals that live on land, you might need many different *orders*, with sub-class objects for each *family*, *genus*, and *species* within each order. 9 | 10 | Python objects defined as classes have a limited set of attributes that apply to that class in the same way the cat family *felidae* has different attributes than the dog family *canidae*. In the family of `OG-Core` macroeconomic model country calibrations, we have many custom objects defined by classes, the most important of which might be the `parameters` class. 11 | 12 | Using objects wisely and efficiently can make your code more readable, easier to modify and use, more scalable, and more interoperable. The iframe below contains a PDF of the BYU ACME open-access lab entitled, "Object-oriented Programming". You can either scroll through the lab on this page using the iframe window, or you can download the PDF for use on your computer. See {cite}`BYUACME_OOP`. {numref}`ExerOOP-acme` below has you work through the problems in this BYU ACME lab. A Python file ([`object_oriented.py`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/ObjectOriented/.py/object_oriented.py)) template for the problems in this lab is stored in the [`./code/ObjectOriented/`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/ObjectOriented) directory. 13 | 14 |
15 | 21 |
22 | 23 | 24 | (SecOOPExercises)= 25 | ## Exercises 26 | 27 | ```{exercise-start} 28 | :label: ExerOOP-acme 29 | :class: green 30 | ``` 31 | Read the BYU ACME "[Object-oriented programming](https://drive.google.com/file/d/1dtDaHYhA_7_6vt_uh60CHIPlHf6CA3qf/view?usp=sharing)" lab and complete Problems 1 through 4 in the lab. {cite}`BYUACME_ExceptIO` 32 | ```{exercise-end} 33 | ``` 34 | 35 | ```{exercise-start} 36 | :label: ExerOOP-defclass 37 | :class: green 38 | ``` 39 | Define a class called `Specifications` with an attribute that is the rate of time preference `beta` (usually represented by the Greek letter $\beta$). Create two instances of this class, the first called `p1` for `beta=0.96` and the second called `p2` for `beta=0.99`. 40 | ```{exercise-end} 41 | ``` 42 | 43 | ```{exercise-start} 44 | :label: ExerOOP-attr 45 | :class: green 46 | ``` 47 | Update the `Specifications` class from {numref}`ExerOOP-defclass` so that it not only allows one to specify the value of `beta` upon instantiation of the class but also checks that `beta` is between 0 and 1. 48 | ```{exercise-end} 49 | ``` 50 | 51 | ```{exercise-start} 52 | :label: ExerOOP-method 53 | :class: green 54 | ``` 55 | Modify the `Specifications` class from {numref}`ExerOOP-attr` so that it has a method that prints the value of `beta`. 56 | ```{exercise-end} 57 | ``` 58 | 59 | ```{exercise-start} 60 | :label: ExerOOP-adjust 61 | :class: green 62 | ``` 63 | Building off the `Specifications` class in {numref}`ExerOOP-method`, change the input of `beta` to the class so that it is input at an annual rate `beta_annual`. Allow another attribute of the class called `S` that is the number of periods in an economic agent's life. Include a method in the `Specifications` class that adjusts the value of `beta` to represent the discount rate applied per model period. Let each model period be `S/80` years, such that each model period equals one years when `S=80`. 64 | ```{exercise-end} 65 | ``` 66 | 67 | ```{exercise-start} 68 | :label: ExerOOP-update 69 | :class: green 70 | ``` 71 | Add a method to the `Specifications` class in {numref}`ExerOOP-adjust` that allows one to update the values of the class attributes `S` and `beta_annual` by providing a dictionary of the form `{"S": 40, "beta_annual": 0.8}`. Ensure that when the instance is updated, the new `beta` attribute is consistent with the new `S` and `beta_annual`. 72 | ```{exercise-end} 73 | ``` 74 | -------------------------------------------------------------------------------- /docs/book/python/StandardLibrary.md: -------------------------------------------------------------------------------- 1 | (Chap_StdLib)= 2 | # Python Standard Library 3 | 4 | This chapter was coauthored by Jason DeBacker and Richard W. Evans. 5 | 6 | The **standard library** of Python is all the built-in functions of the programming language as well as the modules included with the most common Python distributions. The Python online documentation has an [excellent page](https://docs.python.org/3/library/index.html) describing the standard library. These functionalities include built-in [functions](https://docs.python.org/3/library/functions.html), [constants](https://docs.python.org/3/library/constants.html), and [object types](https://docs.python.org/3/library/stdtypes.html), and [data types](https://docs.python.org/3/library/datatypes.html). We recommend that you read these sections in the Python documentation. 7 | 8 | In addition, the iframe below contains a PDF of the BYU ACME open-access lab entitled, "The Standard Library". You can either scroll through the lab on this page using the iframe window, or you can download the PDF for use on your computer. See {cite}`BYUACME_StandardLibrary`. {numref}`ExerStandardLibrary` below has you work through the problems in this BYU ACME lab. The two Python files used in this lab are stored in the [`./code/StandardLibrary/`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/StandardLibrary) directory. 9 | 10 |
11 | 17 |
18 | 19 | 20 | (SecStdLibExercises)= 21 | ## Exercises 22 | 23 | ```{exercise-start} 24 | :label: ExerStandardLibrary 25 | :class: green 26 | ``` 27 | Read the BYU ACME "[The Standard Library](https://drive.google.com/file/d/1JT2TolhLhyQBO2iyGoBZYVPgni0dc3x6/view?usp=sharing)" lab and complete Problems 1 through 5 in the lab. {cite}`BYUACME_StandardLibrary` 28 | ```{exercise-end} 29 | ``` 30 | 31 | ```{exercise-start} 32 | :label: ExerStd-module_run 33 | :class: green 34 | ``` 35 | Create a python module that prints something (e.g. `Hello World!`) and run it from the command line using `python module_name.py`. 36 | ```{exercise-end} 37 | ``` 38 | 39 | ```{exercise-start} 40 | :label: ExerStd-notebook_run 41 | :class: green 42 | ``` 43 | Create a Jupyter notebook (`.ipynb`) with your Python code from {numref}`ExerStd-module_run` and run it in the VS Code text editor. 44 | ```{exercise-end} 45 | ``` 46 | 47 | ```{exercise-start} 48 | :label: ExerStd-def_function 49 | :class: green 50 | ``` 51 | Write a function that finds the Fibonacci sequence up to an integer `N` > 0 in the notebook. Now call this function for `N = 10` and `N=100`. 52 | ```{exercise-end} 53 | ``` 54 | 55 | ```{exercise-start} 56 | :label: ExerStd-sys 57 | :class: green 58 | ``` 59 | Use the `sys` module to create a relative path from a Python module, print that path. 60 | ```{exercise-end} 61 | ``` 62 | -------------------------------------------------------------------------------- /docs/book/python/UnitTesting.md: -------------------------------------------------------------------------------- 1 | (Chap_UnitTesting)= 2 | # Unit Testing 3 | 4 | This chapter was coauthored by Jason DeBacker and Richard W. Evans. 5 | 6 | As a code base expands and the scripts and modules become more interdependent and interconnected, the probability increases that additions to the code will introduce bugs. And as the code base becomes bigger, the harder it can be to find bugs. One of the primary ways to protect the functionality of a code base from bugs is unit testing. 7 | 8 | 9 | (SecUnitTestPytest)= 10 | ## PyTest 11 | 12 | Testing of your source code is important to ensure that the results of your code are accurate and to cut down on debugging time. Fortunately, `Python` has a nice suite of tools for unit testing. In this section, we will introduce the `pytest` package and show how to use it to test your code. 13 | 14 | The iframe below contains a PDF of the BYU ACME open-access lab entitled, "[Unit Testing](https://drive.google.com/file/d/1109ci_tqZz30C2ymf0Hs3UO66l865U0-/view?usp=sharing)". You can either scroll through the lab on this page using the iframe window, or you can download the PDF for use on your computer. See {cite}`BYUACME_UnitTest`. {numref}`ExerTest-acme` below has you work through the problems in this BYU ACME lab. Two Python scripts ([`specs.py`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/UnitTest/specs.py) and [`test_specs.py`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/UnitTest/test_specs.py)) used in the lab are stored in the [`./code/UnitTest/`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/UnitTest) directory. 15 | 16 |
17 | 23 |
24 | 25 | 26 | (SecUnitTestCodecov)= 27 | ## Code coverage 28 | 29 | Ideally, one wants to make sure that all of their source code is tested, thereby ensuring it is producing expected results and reducing the potential that new contributions will introduce bugs. But for any significant code base, it is difficult to know which lines of code are tested and which are. To get an understanding of what is covered by unit tests, packages like [`coverage.py`](https://coverage.readthedocs.io/en/7.3.2/#) can be used to automatically generate a report of code coverage. The report will show which lines of code are covered by unit tests and which are not. This can be useful for identifying parts of the code that need more testing. 30 | 31 | 32 | (SecUnitTestGHActions)= 33 | ## Continuous integration testing and GitHub Actions 34 | 35 | When using GitHub to collaborate with others on a code base, one can leverage the ability to use [GitHub Actions](https://github.com/features/actions) to automate unit testing and code coverage reports (as well as other checks on might want to run). GitHub actions are specified in yaml files and triggered by some set event (e.g., a push, or a pull request, or a chronological schedule). One of the most effective ways to ensure new contributions are not introducing bugs is to run unit tests and code coverage reports on every push to the repository. This can be done by creating a GitHub action that runs the unit tests and code coverage report on every push to the repository. [Codecov](https://about.codecov.io) provides some useful tools for reporting code coverage from unit tests in GitHub Actions. You can see the actions `OG-Core` uses [here](https://github.com/PSLmodels/OG-Core/tree/master/.github/workflows). These include unit tests and coverage reports, as well as checks that documentation builds and then is published upon a merge to the `master` branch. 36 | 37 | 38 | (SecUnitTestExercises)= 39 | ## Exercises 40 | 41 | ```{exercise-start} 42 | :label: ExerTest-acme 43 | :class: green 44 | ``` 45 | Read the BYU ACME "[Unit Testing](https://drive.google.com/file/d/1109ci_tqZz30C2ymf0Hs3UO66l865U0-/view?usp=sharing)" lab and complete Problems 1 through 6 in the lab. {cite}`BYUACME_UnitTest` 46 | ```{exercise-end} 47 | ``` 48 | 49 | ```{exercise-start} 50 | :label: ExerTest-assert_value 51 | :class: green 52 | ``` 53 | In Chapter {ref}`Chap_SciPy`, {numref}`ExerScipy-root-lin`, you wrote wrote a function, and called `SciPy.optimize` to minimize that function. This function had an analytical solution so you could check that SciPy obtained the correct constrained minimum. Now, write a `test_min` function in a module named `test_exercises.py`. This function should end with an assert statement that the minimum value of the function is equal to the analytical solution. Then, run the test using `pytest` and make sure it passes. Note, if your wrote the original function for {numref}`ExerScipy-root-lin` in a notebook, copy it over to a module can save it as `exercises.py`. 54 | ```{exercise-end} 55 | ``` 56 | 57 | ```{exercise-start} 58 | :label: ExerTest-assert_type 59 | :class: green 60 | ``` 61 | Write another test in your `test_exercises.py` module that uses an assert statement to test that the type of the output of your `test_min` function is a NumPy `ndarray` object. Then, run the test using `pytest` and make sure it passes. 62 | ```{exercise-end} 63 | ``` 64 | 65 | ```{exercise-start} 66 | :label: ExerTest-parameterize 67 | :class: green 68 | ``` 69 | Write a simple function that returns the sum of two digits: 70 | ```python 71 | def my_sum(a, b): 72 | return a + b 73 | ``` 74 | Save this in a module called `exercises.py`. Now, use the `@pytest.mark.parametrize` decorator to test a function for multiple inputs of `a` and `b`. 75 | ```{exercise-end} 76 | ``` 77 | 78 | ```{exercise-start} 79 | :label: ExerTest-markers 80 | :class: green 81 | ``` 82 | Use the `@pytest.mark` decorator to mark one of your tests in `test_exercises.py`. Then, your tests using `pytest` but in a way that skips tests with the marker you just gave. 83 | ```{exercise-end} 84 | ``` 85 | -------------------------------------------------------------------------------- /docs/book/python/intro.md: -------------------------------------------------------------------------------- 1 | (Chap_PythonIntro)= 2 | # Introduction to Python 3 | 4 | This chapter was coauthored by Jason DeBacker and Richard W. Evans. 5 | 6 | Many models are written in the Python programming language. Python is the 2nd most widely used language on all GitHub repository projects {cite}`GitHub:2022`, and Python is the 1st most used programming language according to the PYPL ranking of September 2023 {cite}`Stackscale:2023`. 7 | 8 | As these tutorials walk you through the basics of Python, they will leverage some excellent open source materials put together by [QuantEcon](https://quantecon.org/) and the [Applied and Computational Mathematics Emphasis at BYU (BYU ACME)](https://acme.byu.edu/2023-2024-materials). And while the tutorials will point you to those of these other organizations, we have customized all our excercises to be relevant to the work and research of economists. 9 | 10 | 11 | (SecPythonIntroOverview)= 12 | ## Overview of Python 13 | The Python.org site has documentation essays, one of which is entitled "[What is Python? Executive Summary](https://www.python.org/doc/essays/blurb/)". The first paragraph contains the following description. 14 | 15 | > Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed. 16 | 17 | In addition to the description above, Python is an open source programming language that is freely available and customizable (see https://www.python.org/downloads/source/). 18 | 19 | Python has some built in functionality with the standard library, but most of the functionality comes from packages that are developed by the open source community. The most important packages for data science are: NumPy, SciPy, Pandas, and Matplotlib. We will introduce each of these packages as we go through the training materials as they are used heavily in economics applications. 20 | 21 | 22 | (SecPythonIntroInstall)= 23 | ## Installing Python 24 | We recommend that you download the Anaconda distribution of Python provided by [Anaconda](https://www.anaconda.com/download). We also recommend the most recent stable version of Python, which is currently Python 3.11. This can be done from the [Anaconda download page](https://www.anaconda.com/download) for Windows, Mac OSX, and Linux machines. The code we will be writing uses common Python libraries such as `NumPy`, `SciPy`, `pickle`, `os`, `matplotlib`, and `time`, which are all included in the Anaconda distribution. If you are using a different distribution of Python, you may need to install these packages separately. 25 | 26 | 27 | (SecPythonIntroWorkingWith)= 28 | ## Working with Python 29 | 30 | There are several ways to interact with Python: 31 | 1. [Jupyter Notebook](https://jupyter.org/) 32 | 2. iPython session 33 | 3. Running a Python script from the command line 34 | 4. Running a Python script from an IDE such as [Spyder](https://www.spyder-ide.org/). 35 | 36 | In our recommended Python development workflow, you will write Python scripts and modules (`*.py` files) in a text editor. Then you will run those scripts from your terminal. You will want a capable text editor for developing your code. Many capable text editors exist, but we recommend [Visual Studio Code](https://code.visualstudio.com) (VS Code). As you learn Python and complete the exercises in this training program, you will also use Python interactively in a Jupyter Notebook or iPython session. VS Code will be helpful here as well as it will allow you open Jupyter Notebooks and run Python interactively through the text editor. 37 | 38 | VS Code is free and will be included with your installation of Anaconda. This is a very capable text editor and will include syntax highlighting for Python and and built in Git controls. In addition to the basics, you may want to use a more advanced linter for Python. This will help you correct syntax errors on the fly and provide helpful information as you declare objects and call functions. [This link](https://code.visualstudio.com/docs/python/linting) provides step-by-step instructions on using more advanced linting in VS Code. 39 | 40 | Some extensions that we recommend installing into your VS Code: 41 | * cornflakes-linter 42 | * Git Extension Pack 43 | * GitLens 44 | * Jupyter 45 | * Markdown All in One 46 | * Pylance 47 | 48 | In addition, [GitHub Copilot](https://github.com/features/copilot) is an amazing resource and can be added as an extension to VS Code. However, this service is not free of charge and does require an internet connection to work. 49 | 50 | In the iframe below is a PDF of the BYU ACME open-access lab entitled, "Python Intro". You can either scroll through the lab on this page using the iframe window, or you can download the PDF for use on your computer. See {cite}`BYUACME_PythonIntro`. {numref}`ExerPythonIntro` below has you work through the problems in this BYU ACME lab. The Python code file ([`python_intro.py`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/PythonIntro/python_intro.py)) used in the lab is stored in the [`./code/PythonIntro/`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/PythonIntro) directory. 51 | 52 |
53 | 59 |
60 | 61 | We cover Python's built-in functions, constants, and data types and their properties in {numref}`ExerStandardLibrary` of the {ref}`Chap_StdLib` chapter. We also introduce different commonly used objects like Numpy arrays and operations in chapter {ref}`Chap_Numpy` and Pandas DataFrames and operations in chapter {ref}`Chap_Pandas`. 62 | 63 | 64 | (SecPythonIntroPackages)= 65 | ## Python Packages 66 | 67 | Economics applications heavily use a handful of Python packages that will be useful and that these training materials will cover: 68 | 69 | 1. The Standard Library 70 | 2. NumPy for numerical computing (e.g., arrays, linear algebra, etc.) 71 | 3. Pandas for data analysis 72 | 4. Matplotlib for plotting 73 | 5. SciPy for scientific computing (e.g., optimization, interpolation, etc.) 74 | 75 | All of these will be included as part of your installation of Anaconda. Anaconda also includes a package manager called `conda` that will allow you to install additional packages and well help keep versions of packages consistent with each other. We will not cover this in these training materials, but you can find more information about `conda` [here](https://docs.conda.io/en/latest/) and you'll find references to `conda` as we install packages throughout these training materials. 76 | 77 | 78 | (SecPythonIntroTopics)= 79 | ## Python Training Topics 80 | 81 | 1. [Python Standard Library](StandardLibrary.md) 82 | 2. [Exception handling and file input/output](ExceptionsIO.md) 83 | 3. [Object Oriented Programming](OOP.md) 84 | 4. [NumPy](NumPy.md) 85 | 5. [Pandas](Pandas.md) 86 | 6. [Matplotlib](Matplotlib.md) 87 | 7. [SciPy](SciPy.md) 88 | 8. [Doc strings and documentation](DocStrings.md) 89 | 9. [Unit testing](UnitTesting.md) 90 | 91 | 92 | (SecPythonIntroUnix)= 93 | ## (Optional): Using the Unix Shell 94 | 95 | Unix is an old operating system that is the basis for the Linux and Mac operating systems. Many Python users with Mac or Linux operating systems follow a workflow that includes working in the terminal and using Unix commands. This section is optional because Windows terminals do not have the same Unix commands. For those interested, feel free to work through the Unix lab below from BYU ACME. This lab features great examples and instruction, and also has seven good exercises for you to practice on. 96 | 97 | In the iframe below is a PDF of the BYU ACME open-access lab entitled, "Unix Shell 1: Introduction". You can either scroll through the lab on this page using the iframe window, or you can download the PDF for use on your computer. See {cite}`BYUACME_Unix1`. {numref}`ExerUnix1` below has you work through the problems in this BYU ACME lab. The shell script file ([`unixshell1.sh`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/UnixShell1/unixshell1.sh)) used in the lab, along with the associated zip file ([`Shell1.zip`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/UnixShell1/Shell1.zip)), are stored in the [`./code/UnixShell1/`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/UnixShell1) directory. 98 | 99 |
100 | 106 |
107 | 108 | (SecPythonIntroExercises)= 109 | ## Exercises 110 | 111 | ```{exercise-start} Python introduction 112 | :label: ExerPythonIntro 113 | :class: green 114 | ``` 115 | Read the BYU ACME "[Introduction to Python](https://drive.google.com/file/d/1CHl8C-QKgs8jHzsRfJSMWkVqq0elzP1F/view?usp=sharing)" lab and complete Problems 1 through 8 in the lab. {cite}`BYUACME_PythonIntro` 116 | ```{exercise-end} 117 | ``` 118 | 119 | ```{exercise-start} OPTIONAL: Unix shell commands 120 | :label: ExerUnix1 121 | :class: green 122 | ``` 123 | Read the BYU ACME "[Unix Shell 1: Introduction](https://drive.google.com/file/d/18eTLp_FhWFYgAItIZnX6gesIvg91rXW5/view?usp=sharing)" lab and complete Problems 1 through 7 in the lab. {cite}`BYUACME_Unix1` 124 | ```{exercise-end} 125 | ``` 126 | -------------------------------------------------------------------------------- /docs/book/struct_est/intro.md: -------------------------------------------------------------------------------- 1 | 2 | (Chap_StructEstIntro)= 3 | # Introduction to Structural Estimation 4 | 5 | > ``You keep using that word. I do not think it means what you think it means." Inigo Montoya, *The Princess Bride* 6 | 7 | The term ``structural estimation" has been the source of debate in the economics profession. [TODO: Insert some of the debate here.] 8 | 9 | The material for the chapters in this Structural Estimation section was initially developed in the Structural Estimation course I taught in the Masters in Computational Social Science program at the University of Chicago from 2017 to 2020.[^MACSScourses] 10 | 11 | A good place to start in describing structural estimation is the definition of a {term}`model`. 12 | 13 | ```{prf:definition} Model 14 | :label: DefStructEst_Model 15 | 16 | A **model** is a set of cause and effect mathematical relationships, often specified with parameters $\theta$, among data $x$ or $(x,y)$ used to understand, explain, and predict phenomena. A model might be specified as, 17 | \begin{equation*} 18 | g(x,\theta) = 0 \quad\text{or}\quad y = g(x,\theta) 19 | \end{equation*} 20 | where $g$ is a function or vector of functions that represents the mathematical relationships between variables and parameters. 21 | ``` 22 | 23 | ```{prf:definition} Exogenous variables 24 | :label: DefStructEst_ExogVar 25 | 26 | **Exogenous variables** are inputs to the model, taken as given, or from outside the model. These can include both data $x$ and parameters $\theta$. 27 | ``` 28 | 29 | ```{prf:definition} Endogenous variables 30 | :label: DefStructEst_EndogVar 31 | 32 | * **Endogenous variables** are outputs of the model or dependent on exogenous variables. These can include portions of the data $x$, sometimes designated as $y$ as in $y = g(x,\theta)$. 33 | ``` 34 | 35 | ```{prf:definition} Data generating process (DGP) 36 | :label: DefStructEst_DGP 37 | 38 | The broadest definition of a **data generating process** (DGP) is a complete description of the mechanism that causes some observed phenomenon with all its dependencies. Unfortunately, in most realistic systems, this definition is too complex. A more practical definition of a **data generating process** is a simplified version of the process that causes some observed phenomenon with its key dependencies. The concept of a DGP is very similar to the concept of a {term}`model` from {prf:ref}`DefStructEst_Model`. A key characteristic of a DGP is that it must be specified in such as way that it could be used to simulate data. 39 | ``` 40 | 41 | ```{prf:definition} Structural model 42 | :label: DefStructEst_StructMod 43 | 44 | A **structural model** in economics is a model in which the mathematical relationships among variables and parameters are derived from individuals', firms', or other organizations' optimization. These are often referred to as behavioral equations. **Structural models** can include linear models and linear approximations. But most often, **structural models** are nonlinear and dynamic. 45 | ``` 46 | 47 | ```{prf:definition} Reduced form model 48 | :label: DefStructEst_ReducedMod 49 | 50 | A **reduced form model** in economics is a model in which the equations are either not derived from behavioral equations or are only implicitly a linear approximation of some more complicated model. However, because they are atheoretical and often nonparametric, machine learning models can be categorized as reduced form. **Reduced form models** are most often static, although time series econometric models are categorized as reduced form. 51 | ``` 52 | 53 | ```{prf:definition} Structural estimation 54 | :label: DefStructEst_StructEst 55 | 56 | Put definition of **structural estimation** here. 57 | ``` 58 | 59 | ```{prf:definition} Calibration 60 | :label: DefStructEst_Calib 61 | 62 | Put definition of **calibration** here. 63 | ``` 64 | 65 | ```{prf:definition} Reduced form estimation 66 | :label: DefStructEst_ReducedEst 67 | 68 | Put definition of **reduced form estimation** here. 69 | ``` 70 | 71 | (SecStructEstIntroTypes)= 72 | ## Different types of models 73 | A good introduction to structural estimation is to compare it to other types of research designs. {numref}`ExercStructEst_CompPaper` asks you to compare the structural approach to the reduced form approach. The following are some prominent research designs in economics, only some of which are structural estimations. 74 | 75 | **Structural estimation papers** 76 | * (Classic structural estimation) {cite}`Rust:1987` 77 | * {cite}`BarskySims:2012` 78 | 79 | **Reduced form estimation papers** 80 | * {cite}`BaileyEtAl:2019` 81 | * (Theory and reduced form and randomized controlled trial (RCT)) {cite}`AttanasioEtAl:2020` 82 | 83 | **Theory** 84 | * {cite}`StraubWerning:2020` 85 | 86 | 87 | (SecStructEstIntroExerc)= 88 | ## Exercises 89 | 90 | ```{exercise} Persuasive short paper on structural estimation 91 | :label: ExercStructEst_CompPaper 92 | :class: green 93 | 94 | **Persuasive short paper supporting either structural estimation or reduced form estimation or both.** 95 | * Read {cite}`Keane:2010` and {cite}`Rust:2010`. 96 | * Write a short persuasive paper of about one page (maximum of 1.5 pages) in which you make your case for either structural estimation or reduced form estimation or both. Note that both Keane and Rust are biased toward structural estimation. 97 | * Make sure that you cite arguments that they use as evidence for or against your thesis. 98 | * Refute (or temper) at least one of their arguments. 99 | ``` 100 | 101 | 102 | (SecStructEstIntroFootnotes)= 103 | ## Footnotes 104 | 105 | The footnotes from this chapter. 106 | 107 | [^MACSScourses]: I taught a course, entitled Structural Estimation, to graduate students, with a few advanced undergradutates, in the Masters in Computational Social Science program at the University of Chicago four times from 2017 to 2020. The content of each course is in the following GitHub repositories, with syllabi, lecture slides, Jupyter notebooks, tests, and problem sets: [Winter 2017](https://github.com/rickecon/StructEst_W17), [Winter 2018](https://github.com/rickecon/StructEst_W18), [Winter 2019](https://github.com/rickecon/StructEst_W19), and [Winter 2020](https://github.com/rickecon/StructEst_W20). 108 | -------------------------------------------------------------------------------- /docs/book/struct_est/paper.md: -------------------------------------------------------------------------------- 1 | 2 | (Chap_StructEstPaper)= 3 | # Writing a Structural Estimation Paper 4 | 5 | TODO: Finish this section. The content for this section will be taken from my course slides on [creating a structural estimation paper proposal](https://github.com/rickecon/StructEst_W20/blob/master/Projects/ProposalPresent.pdf), and my slides on how to write the following sections of the paper: [data description](https://github.com/rickecon/StructEst_W20/blob/master/Projects/DataSection_slides.pdf), [model description](https://github.com/rickecon/StructEst_W20/blob/master/Projects/ModelDescr_slides.pdf), [estimation section](https://github.com/rickecon/StructEst_W20/blob/master/Projects/EstimResults_slides.pdf), and [conclusion/intro/abstract](https://github.com/rickecon/StructEst_W20/blob/master/Projects/IntroAbsConcl_slides.pdf). 6 | 7 | 8 | (SecStructEstPaperSections)= 9 | ## Sections of a structural estimation project 10 | 11 | TODO: Include discussion from project sections and order of project slide in [creating a structural estimation paper proposal](https://github.com/rickecon/StructEst_W20/blob/master/Projects/ProposalPresent.pdf) slides. 12 | 13 | 14 | (SecStructEstPaperSect_Data)= 15 | ### Data description 16 | 17 | See [data description](https://github.com/rickecon/StructEst_W20/blob/master/Projects/DataSection_slides.pdf) slides, 18 | 19 | 20 | (SecStructEstPaperSect_Model)= 21 | ### Model description 22 | 23 | See [model description](https://github.com/rickecon/StructEst_W20/blob/master/Projects/ModelDescr_slides.pdf) slides. 24 | 25 | 26 | (SecStructEstPaperSect_Est)= 27 | ### Estimation 28 | 29 | See [estimation section](https://github.com/rickecon/StructEst_W20/blob/master/Projects/EstimResults_slides.pdf) slides. 30 | 31 | 32 | (SecStructEstPaperSect_Concl)= 33 | ### Conclusion, intro, abstract 34 | 35 | See [conclusion/intro/abstract](https://github.com/rickecon/StructEst_W20/blob/master/Projects/IntroAbsConcl_slides.pdf) slides. 36 | 37 | 38 | (SecStructEstPaperFind)= 39 | ## Where/how do I find a project? 40 | 41 | TODO: Include discussion from ending slides in [creating a structural estimation paper proposal](https://github.com/rickecon/StructEst_W20/blob/master/Projects/ProposalPresent.pdf) slides. Make sure to include discussion of replication versus original research. 42 | 43 | 44 | (SecStructEstPaperExerc)= 45 | ## Exercises 46 | 47 | ```{exercise} Create a structural estimation project proposal 48 | :label: ExercStructEst_PaperProposal 49 | :class: green 50 | 51 | Create a 5-minute slide presentation of a structural estimation project proposal. You can work alone. However, I recommend you work in a group of (at most) two. The focus of your proposal presentation must be a research question. A good project will have a strong economic theory component. Structural estimation is taking economic theory directly to data. To estimate your model, your project must use GMM, MLE, SMM, or SMLE that you code yourself. I have included a LaTeX beamer style slides template in the [`./code/StrEstPaper/LaTeXtemplates/`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/StrEstPaper/LaTeXtemplates) folder of the GitHub repository for this online book if you want to do your slides in LaTeX. Your proposal should include the following requirements. 52 | 53 | 1. Restrictions 54 | * The focus of your proposal presentation must be a research question. No "methods for the sake of methods" projects. 55 | * You are not allowed to use linear regressions *unless*: 56 | * it is involved in an indirect inference estimation 57 | * it is a small subroutine of a bigger model 58 | 59 | 2. State the research question. 60 | * What are you trying to learn by using this model? 61 | * Question should be focused. A narrow question is usually better than a broad question. 62 | 63 | 3. Describe the model (the data generating process, DGP) $F(x_t,z_t|\theta)=0$ 64 | * What are the endogenous variables $x_t$? 65 | * What are the exogenous variables $z_t$? 66 | * What are the parameters $\theta$? 67 | * Which parameters are estimated $\hat{\theta}_e$? 68 | * Which parameters are calibrated $\bar{\theta}_c? 69 | * How does one solve the model given $\theta$? 70 | * Equations are sufficient (e.g., econometric models) 71 | * Analytical solution (e.g., behavioral models) 72 | * Computational solution (e.g., macroeconomic models) 73 | 74 | 4. Describe the proposed data source $X$ 75 | * How available are the data? 76 | * Can you show some initial descriptive statistics or visualizations? 77 | 78 | 5. Describe your proposed estimation strategy $\hat{\theta}$ 79 | * Why did you choose this estimation strategy over alternatives? 80 | * How will you identify your parameters? 81 | * MLE: Likelihood function 82 | * GMM: What moments will you use? 83 | 84 | 6. Proposal conclusion 85 | * Restate your research question 86 | * Outline your hopes and dreams for the project 87 | * Identify potential shortcomings/alternatives 88 | ``` 89 | 90 | ```{exercise} Structural estimation project paper 91 | :label: ExercStructEst_Paper 92 | :class: green 93 | 94 | Write a structural estimation paper based on your project proposal from {numref}`ExercStructEst_PaperProposal` using the examples and suggestions from this chapter. I have posted a LaTeX template for a paper in the [`./code/StrEstPaper/LaTeXtemplates/`](https://github.com/OpenSourceEcon/CompMethods/tree/main/code/StrEstPaper/LaTeXtemplates) folder of the GitHub repository for this online book if you want to do your paper in LaTeX. 95 | 96 | 1. There is no minimum page requirement, but your paper should be no more than 20 pages long. You can put any extra information in a technical appendix that is not subject to the maximum page requirement. 97 | 2. Your paper should be focused on a research question, have a title, clear indication of authors, date, and abstract. 98 | 3. You must perform a structural estimation in your paper using one of the following methods: GMM, MLE, SMM, or SMLE that you code yourself. 99 | 4. The body of your paper should have the following sections, and you should follow the examples and recommendations for those sections from the corresponding discussions in this chapter. 100 | * Introduction 101 | * Data description 102 | * Model description 103 | * Estimation 104 | * Conclusion 105 | ``` 106 | 107 | 108 | (SecStructEstPaperFootnotes)= 109 | ## Footnotes 110 | 111 | The footnotes from this chapter. 112 | -------------------------------------------------------------------------------- /docs/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/docs/favicon.ico -------------------------------------------------------------------------------- /environment.yml: -------------------------------------------------------------------------------- 1 | name: compmethods-dev 2 | channels: 3 | - conda-forge 4 | dependencies: 5 | - python>=3.10 6 | - numpy 7 | - scipy 8 | - pandas 9 | - ipython 10 | - matplotlib 11 | - bokeh 12 | - sphinx 13 | - sphinx-argparse 14 | - sphinxcontrib-bibtex>=2.0.0 15 | - sphinx-math-dollar 16 | - pydata-sphinx-theme 17 | - jupyter-book>=0.11.3 18 | - jupyter 19 | - black 20 | - setuptools 21 | - pytest 22 | - coverage 23 | - pip 24 | - pip: 25 | - linecheck 26 | - yaml-changelog 27 | - sphinx-exercise 28 | - sphinx-proof 29 | -------------------------------------------------------------------------------- /images/basic_empirics/basic_empirics/AcemogluEtAl_fig2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/basic_empirics/basic_empirics/AcemogluEtAl_fig2.png -------------------------------------------------------------------------------- /images/basic_empirics/basic_empirics/AcemogluEtAl_predvals.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/basic_empirics/basic_empirics/AcemogluEtAl_predvals.png -------------------------------------------------------------------------------- /images/basic_empirics/basic_empirics/CorrVsCaus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/basic_empirics/basic_empirics/CorrVsCaus.png -------------------------------------------------------------------------------- /images/basic_empirics/basic_empirics/scatter1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/basic_empirics/basic_empirics/scatter1.png -------------------------------------------------------------------------------- /images/basic_empirics/basic_empirics/scatter2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/basic_empirics/basic_empirics/scatter2.png -------------------------------------------------------------------------------- /images/basic_empirics/basic_empirics/scatter3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/basic_empirics/basic_empirics/scatter3.png -------------------------------------------------------------------------------- /images/basic_empirics/logit/Fig2_14.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/basic_empirics/logit/Fig2_14.png -------------------------------------------------------------------------------- /images/basic_empirics/logit/Fig2_15.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/basic_empirics/logit/Fig2_15.png -------------------------------------------------------------------------------- /images/basic_empirics/logit/Fig2_16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/basic_empirics/logit/Fig2_16.png -------------------------------------------------------------------------------- /images/basic_empirics/logit/age_boxplot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/basic_empirics/logit/age_boxplot.png -------------------------------------------------------------------------------- /images/basic_empirics/logit/logit_gen.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/basic_empirics/logit/logit_gen.png -------------------------------------------------------------------------------- /images/basic_empirics/logit/survived_count.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/basic_empirics/logit/survived_count.png -------------------------------------------------------------------------------- /images/gmm/Econ381Scores_SurfaceCrit4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/gmm/Econ381Scores_SurfaceCrit4.png -------------------------------------------------------------------------------- /images/gmm/Econ381scores_2MLEs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/gmm/Econ381scores_2MLEs.png -------------------------------------------------------------------------------- /images/gmm/Econ381scores_4mom2mom.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/gmm/Econ381scores_4mom2mom.png -------------------------------------------------------------------------------- /images/gmm/Econ381scores_SurfaceCrit1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/gmm/Econ381scores_SurfaceCrit1.png -------------------------------------------------------------------------------- /images/gmm/Econ381scores_SurfaceCrit4_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/gmm/Econ381scores_SurfaceCrit4_2.png -------------------------------------------------------------------------------- /images/gmm/hist_inc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/gmm/hist_inc.png -------------------------------------------------------------------------------- /images/mle/Econ381scores_2truncs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/mle/Econ381scores_2truncs.png -------------------------------------------------------------------------------- /images/mle/Econ381scores_MLE.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/mle/Econ381scores_MLE.png -------------------------------------------------------------------------------- /images/mle/Econ381scores_MLEconstr.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/mle/Econ381scores_MLEconstr.png -------------------------------------------------------------------------------- /images/mle/Econ381scores_SurfaceLogLike.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/mle/Econ381scores_SurfaceLogLike.png -------------------------------------------------------------------------------- /images/mle/Econ381scores_SurfaceLogLikeZoom.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/mle/Econ381scores_SurfaceLogLikeZoom.png -------------------------------------------------------------------------------- /images/mle/Econ381scores_hist.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/mle/Econ381scores_hist.png -------------------------------------------------------------------------------- /images/mle/GBtree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/mle/GBtree.png -------------------------------------------------------------------------------- /images/smm/Econ381_crit1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/smm/Econ381_crit1.png -------------------------------------------------------------------------------- /images/smm/Econ381_crit4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/smm/Econ381_crit4.png -------------------------------------------------------------------------------- /images/smm/Econ381scores_sim1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/smm/Econ381scores_sim1.png -------------------------------------------------------------------------------- /images/smm/Econ381scores_smm1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/smm/Econ381scores_smm1.png -------------------------------------------------------------------------------- /images/smm/Econ381scores_smm4_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/smm/Econ381scores_smm4_1.png -------------------------------------------------------------------------------- /images/smm/Econ381scores_truncnorm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSourceEcon/CompMethods/9803d3eb10ece3f2aa4d553f6b0c8fde40e2fd13/images/smm/Econ381scores_truncnorm.png -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """This file contains the CompMethods package's metadata and dependencies.""" 2 | 3 | from setuptools import find_packages, setup 4 | 5 | with open("README.md", "r") as readme_file: 6 | readme = readme_file.read() 7 | 8 | setup( 9 | name="CompMethods", 10 | version="0.1.0", 11 | author="Richard W. Evans", 12 | author_email="rickecon@gmail.com", 13 | long_description=readme, 14 | long_description_content_type="text/markdown", 15 | classifiers=[ 16 | "Development Status :: 5 - Production/Stable", 17 | "License :: OSI Approved :: GNU Affero General Public License v3", 18 | "Operating System :: POSIX", 19 | "Programming Language :: Python", 20 | "Programming Language :: Python :: 3.10", 21 | "Topic :: Scientific/Engineering :: Information Analysis", 22 | ], 23 | description="Computational Methods for Economists using Python", 24 | keywords="code python git github data science python regression causal inference structural estimation machine learning neural networks deep learning statistics econometrics", 25 | license="http://www.fsf.org/licensing/licenses/agpl-3.0.html", 26 | url="https://github.com/OpenSourceEcon/CompMethods", 27 | include_package_data=True, # Will read MANIFEST.in 28 | install_requires=[ 29 | "numpy", 30 | "scipy", 31 | "pandas", 32 | "ipython", 33 | "matplotlib", 34 | "bokeh", 35 | "sphinx", 36 | "sphinx-argparse", 37 | "sphinx-exercise", 38 | "sphinx-proof", 39 | "sphinxcontrib-bibtex>=2.0.0", 40 | "sphinx-math-dollar", 41 | "pydata-sphinx-theme", 42 | "jupyter-book>=0.11.3", 43 | "jupyter", 44 | "black", 45 | "setuptools", 46 | "pytest", 47 | "coverage", 48 | "linecheck", 49 | "yaml-changelog", 50 | ], 51 | python_requires=">=3.10", 52 | tests_require=["pytest"], 53 | packages=find_packages(), 54 | ) 55 | -------------------------------------------------------------------------------- /tests/test_add_junk.py: -------------------------------------------------------------------------------- 1 | # import sys 2 | 3 | # sys.path.append("/Users/richardevans/Docs/Economics/OSE/CompMethods/code/") 4 | 5 | import pytest 6 | 7 | # from junk_funcs import junk_func_add 8 | 9 | 10 | def junk_func_add(arg1, arg2): 11 | """ 12 | This is just a junk function that duplicates the `junk_funcs.py` module in 13 | the `/code/` directory. We can delete this as soon as we have some real 14 | functions. 15 | """ 16 | junk_sum = arg1 + arg2 17 | 18 | return junk_sum 19 | 20 | 21 | @pytest.mark.parametrize( 22 | "arg1, arg2, expected", 23 | [(2, 3, 5), (10, 17, 27)], 24 | ids=[ 25 | "2 plus 3 equals 5", 26 | "10 plus 17 equals 27", 27 | ], 28 | ) 29 | def test_junk_func_add(arg1, arg2, expected): 30 | """ 31 | This is just a fake test of code in the `/code/` directory. We can delete 32 | this as soon as we have some real tests. 33 | """ 34 | junk_sum = junk_func_add(arg1, arg2) 35 | 36 | assert junk_sum == expected 37 | --------------------------------------------------------------------------------