diff --git a/.github/workflows/cache.yml b/.github/workflows/cache.yml deleted file mode 100644 index e2f45418..00000000 --- a/.github/workflows/cache.yml +++ /dev/null @@ -1,52 +0,0 @@ -name: Build Cache [using jupyter-book] -on: - push: - branches: - - main -jobs: - tests: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Setup Anaconda - uses: conda-incubator/setup-miniconda@v3 - with: - auto-update-conda: true - auto-activate-base: true - miniconda-version: 'latest' - python-version: "3.12" - environment-file: environment.yml - activate-environment: quantecon - - name: graphviz Support # TODO: required? - run: | - sudo apt-get -qq update && sudo apt-get install -y graphviz - - name: Install latex dependencies - run: | - sudo apt-get -qq update - sudo apt-get install -y \ - texlive-latex-recommended \ - texlive-latex-extra \ - texlive-fonts-recommended \ - texlive-fonts-extra \ - texlive-xetex \ - latexmk \ - xindy \ - dvipng \ - cm-super - - name: Build HTML - shell: bash -l {0} - run: | - jb build lectures --path-output ./ -W --keep-going - - name: Upload Execution Reports (HTML) - uses: actions/upload-artifact@v4 - if: failure() - with: - name: execution-reports - path: _build/html/reports - - name: Upload "_build" folder (cache) - uses: actions/upload-artifact@v4 - with: - name: build-cache - path: _build - include-hidden-files: true \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml deleted file mode 100644 index 2ab95026..00000000 --- a/.github/workflows/ci.yml +++ /dev/null @@ -1,89 +0,0 @@ -name: Build HTML [using jupyter-book] -on: [pull_request] -jobs: - preview: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Setup Anaconda - uses: conda-incubator/setup-miniconda@v3 - with: - auto-update-conda: true - auto-activate-base: true - miniconda-version: 'latest' - python-version: "3.12" - environment-file: environment.yml - activate-environment: quantecon - - name: Graphics Support #TODO: Review if graphviz is needed - run: | - sudo apt-get -qq update && sudo apt-get install -y graphviz - - name: Install latex dependencies - run: | - sudo apt-get -qq update - sudo apt-get install -y \ - texlive-latex-recommended \ - texlive-latex-extra \ - texlive-fonts-recommended \ - texlive-fonts-extra \ - texlive-xetex \ - latexmk \ - xindy \ - dvipng \ - cm-super - - name: Display Conda Environment Versions - shell: bash -l {0} - run: conda list - - name: Display Pip Versions - shell: bash -l {0} - run: pip list - - name: Download "build" folder (cache) - uses: dawidd6/action-download-artifact@v8 - with: - workflow: cache.yml - branch: main - name: build-cache - path: _build - # Build Assets (Download Notebooks and PDF via LaTeX) - - name: Build PDF from LaTeX - shell: bash -l {0} - run: | - jb build lectures --builder pdflatex --path-output ./ -n --keep-going - mkdir -p _build/html/_pdf - cp -u _build/latex/*.pdf _build/html/_pdf - - name: Upload Execution Reports (LaTeX) - uses: actions/upload-artifact@v4 - if: failure() - with: - name: execution-reports - path: _build/latex/reports - - name: Build Download Notebooks (sphinx-tojupyter) - shell: bash -l {0} - run: | - jb build lectures --path-output ./ --builder=custom --custom-builder=jupyter - mkdir -p _build/html/_notebooks - cp -u _build/jupyter/*.ipynb _build/html/_notebooks - # Build HTML (Website) - # BUG: rm .doctress to remove `sphinx` rendering issues for ipywidget mimetypes - # and clear the sphinx cache for building final HTML documents. - - name: Build HTML - shell: bash -l {0} - run: | - rm -r _build/.doctrees - jb build lectures --path-output ./ -nW --keep-going - - name: Upload Execution Reports (HTML) - uses: actions/upload-artifact@v4 - if: failure() - with: - name: execution-reports - path: _build/html/reports - - name: Preview Deploy to Netlify - uses: nwtgck/actions-netlify@v3.0 - with: - publish-dir: '_build/html/' - production-branch: main - github-token: ${{ secrets.GITHUB_TOKEN }} - deploy-message: "Preview Deploy from GitHub Actions" - env: - NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }} - NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }} diff --git a/.github/workflows/collab.yml b/.github/workflows/collab.yml deleted file mode 100644 index 5060c30b..00000000 --- a/.github/workflows/collab.yml +++ /dev/null @@ -1,54 +0,0 @@ -name: Build Project on Google Collab (Execution) -on: [pull_request] - -jobs: - test: - runs-on: quantecon-large - container: - image: us-docker.pkg.dev/colab-images/public/runtime:latest - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ github.event.pull_request.head.sha }} - - name: Check for dockerenv file - run: (ls /.dockerenv && echo Found dockerenv) || (echo No dockerenv) - - name: Check python version - shell: bash -l {0} - run: | - python --version - - name: Display Pip Versions - shell: bash -l {0} - run: pip list - - name: Download "build" folder (cache) - uses: dawidd6/action-download-artifact@v8 - with: - workflow: cache.yml - branch: main - name: build-cache - path: _build - # Install build software - - name: Install Build Software - shell: bash -l {0} - run: | - pip install jupyter-book==0.15.1 docutils==0.17.1 quantecon-book-theme==0.7.2 sphinx-tojupyter==0.3.0 sphinxext-rediraffe==0.2.7 sphinx-exercise==0.4.1 sphinxcontrib-youtube==1.1.0 sphinx-togglebutton==0.3.1 arviz==0.13.0 sphinx_proof==0.2.0 sphinx_reredirects==0.1.3 - # Build of HTML (Execution Testing) - - name: Build HTML - shell: bash -l {0} - run: | - jb build lectures --path-output ./ -n -W --keep-going - - name: Upload Execution Reports - uses: actions/upload-artifact@v4 - if: failure() - with: - name: execution-reports - path: _build/html/reports - - name: Preview Deploy to Netlify - uses: nwtgck/actions-netlify@v3.0 - with: - publish-dir: '_build/html/' - production-branch: main - github-token: ${{ secrets.GITHUB_TOKEN }} - deploy-message: "Preview Deploy from GitHub Actions" - env: - NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }} - NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }} diff --git a/.github/workflows/linkcheck.yml b/.github/workflows/linkcheck.yml deleted file mode 100644 index 226685c1..00000000 --- a/.github/workflows/linkcheck.yml +++ /dev/null @@ -1,44 +0,0 @@ -name: Link Checker [Anaconda, Linux] -on: - pull_request: - types: [opened, reopened] - schedule: - # UTC 12:00 is early morning in Australia - - cron: '0 12 * * *' -jobs: - link-check-linux: - name: Link Checking (${{ matrix.python-version }}, ${{ matrix.os }}) - runs-on: ${{ matrix.os }} - strategy: - fail-fast: false - matrix: - os: ["ubuntu-latest"] - python-version: ["3.12"] - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Setup Anaconda - uses: conda-incubator/setup-miniconda@v3 - with: - auto-update-conda: true - auto-activate-base: true - miniconda-version: 'latest' - python-version: "3.12" - environment-file: environment.yml - activate-environment: quantecon - - name: Download "build" folder (cache) - uses: dawidd6/action-download-artifact@v8 - with: - workflow: cache.yml - branch: main - name: build-cache - path: _build - - name: Link Checker - shell: bash -l {0} - run: jb build lectures --path-output=./ --builder=custom --custom-builder=linkcheck - - name: Upload Link Checker Reports - uses: actions/upload-artifact@v4 - if: failure() - with: - name: linkcheck-reports - path: _build/linkcheck \ No newline at end of file diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml deleted file mode 100644 index 2054c6f2..00000000 --- a/.github/workflows/publish.yml +++ /dev/null @@ -1,114 +0,0 @@ -name: Build & Publish to GH-PAGES -on: - push: - tags: - - 'publish*' -jobs: - publish: - if: github.event_name == 'push' && startsWith(github.event.ref, 'refs/tags') - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Setup Anaconda - uses: conda-incubator/setup-miniconda@v3 - with: - auto-update-conda: true - auto-activate-base: true - miniconda-version: 'latest' - python-version: "3.12" - environment-file: environment.yml - activate-environment: quantecon - - name: Install latex dependencies - run: | - sudo apt-get -qq update - sudo apt-get install -y \ - texlive-latex-recommended \ - texlive-latex-extra \ - texlive-fonts-recommended \ - texlive-fonts-extra \ - texlive-xetex \ - latexmk \ - xindy \ - dvipng \ - cm-super - - name: Display Conda Environment Versions - shell: bash -l {0} - run: conda list - - name: Display Pip Versions - shell: bash -l {0} - run: pip list - - name: Download "build" folder (cache) - uses: dawidd6/action-download-artifact@v8 - with: - workflow: cache.yml - branch: main - name: build-cache - path: _build - # Build Assets (Download Notebooks and PDF via LaTeX) - - name: Build PDF from LaTeX - shell: bash -l {0} - run: | - jb build lectures --builder pdflatex --path-output ./ -n --keep-going - - name: Copy LaTeX PDF for GH-PAGES - shell: bash -l {0} - run: | - mkdir -p _build/html/_pdf - cp -u _build/latex/*.pdf _build/html/_pdf - - name: Build Download Notebooks (sphinx-tojupyter) - shell: bash -l {0} - run: | - jb build lectures --path-output ./ --builder=custom --custom-builder=jupyter - - name: Copy Download Notebooks for GH-PAGES - shell: bash -l {0} - run: | - mkdir -p _build/html/_notebooks - cp -u _build/jupyter/*.ipynb _build/html/_notebooks - # Build HTML (Website) - # BUG: rm .doctress to remove `sphinx` rendering issues for ipywidget mimetypes - # and clear the sphinx cache for building final HTML documents. - - name: Build HTML - shell: bash -l {0} - run: | - rm -r _build/.doctrees - jb build lectures --path-output ./ - - name: Deploy to Netlify - uses: nwtgck/actions-netlify@v3.0 - with: - publish-dir: '_build/html/' - production-branch: main - github-token: ${{ secrets.GITHUB_TOKEN }} - deploy-message: "Deploy from GitHub Actions" - env: - NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }} - NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }} - - name: Deploy website to gh-pages - uses: peaceiris/actions-gh-pages@v4 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - publish_dir: _build/html/ - cname: intro.quantecon.org - - name: Upload "_build" folder (cache) - uses: actions/upload-artifact@v4 - with: - name: build-publish - path: _build - # Sync notebooks - - name: Prepare lecture-python-intro.notebooks sync - shell: bash -l {0} - run: | - mkdir -p _build/lecture-python-intro.notebooks - cp -a _notebook_repo/. _build/lecture-python-intro.notebooks - cp _build/jupyter/*.ipynb _build/lecture-python-intro.notebooks - ls -a _build/lecture-python-intro.notebooks - - name: Commit latest notebooks to lecture-python-intro.notebooks - uses: cpina/github-action-push-to-another-repository@main - env: - API_TOKEN_GITHUB: ${{ secrets.QUANTECON_SERVICES_PAT }} - with: - source-directory: '_build/lecture-python-intro.notebooks/' - destination-repository-username: 'QuantEcon' - destination-repository-name: 'lecture-python-intro.notebooks' - commit-message: 'auto publishing updates to notebooks' - destination-github-username: 'quantecon-services' - user-email: services@quantecon.org diff --git a/.github/workflows/wasm_test.yml b/.github/workflows/wasm_test.yml new file mode 100644 index 00000000..545479f8 --- /dev/null +++ b/.github/workflows/wasm_test.yml @@ -0,0 +1,47 @@ +name: test-wasm + +on: + push: + branches: + - wasm + pull_request: + branches: + - wasm + +jobs: + run-wasm-test: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: "3.12" + + - name: Install libraries + run: | + python -m pip install pyodide-build jupytext + pyodide xbuildenv install + pyodide venv .venv-pyodide + + - name: Convert lectures to python files + run: python testing/generate_py_files.py + + - name: Pip and Python (venv) + run: | + source .venv-pyodide/bin/activate + which pip + which python + + - name: Import libraries in pyodide + run: | + source .venv-pyodide/bin/activate + python testing/install_pyodide_libs.py + + - name: Run python files in pyodide environment + run: | + source .venv-pyodide/bin/activate + bash testing/run_py_files.sh testing/py_files diff --git a/.gitignore b/.gitignore index f94768ac..9d4df66a 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ lectures/_build .ipynb_checkpoints/ .virtual_documents/ _build/* +testing/py_files/* diff --git a/lectures/ar1_processes.md b/lectures/ar1_processes.md index 34b93ae7..406ead94 100644 --- a/lectures/ar1_processes.md +++ b/lectures/ar1_processes.md @@ -3,8 +3,10 @@ jupytext: text_representation: extension: .md format_name: myst + format_version: 0.13 + jupytext_version: 1.16.1 kernelspec: - display_name: Python 3 + display_name: Python 3 (ipykernel) language: python name: python3 --- @@ -40,7 +42,7 @@ partly because they help us understand important concepts. Let's start with some imports: -```{code-cell} ipython +```{code-cell} ipython3 import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = (11, 5) #set default figure size @@ -160,7 +162,7 @@ The following code uses these facts to track the sequence of marginal distributi The parameters are -```{code-cell} python3 +```{code-cell} ipython3 a, b, c = 0.9, 0.1, 0.5 mu, v = -3.0, 0.6 # initial conditions mu_0, v_0 @@ -168,7 +170,7 @@ mu, v = -3.0, 0.6 # initial conditions mu_0, v_0 Here's the sequence of distributions: -```{code-cell} python3 +```{code-cell} ipython3 from scipy.stats import norm sim_length = 10 @@ -188,8 +190,6 @@ ax.legend(bbox_to_anchor=[1.05,1],loc=2,borderaxespad=1) plt.show() ``` - - ## Stationarity and asymptotic stability When we use models to study the real world, it is generally preferable that our @@ -206,7 +206,7 @@ Notice that, in the figure above, the sequence $\{ \psi_t \}$ seems to be conver This is even clearer if we project forward further into the future: -```{code-cell} python3 +```{code-cell} ipython3 def plot_density_seq(ax, mu_0=-3.0, v_0=0.6, sim_length=40): mu, v = mu_0, v_0 for t in range(sim_length): @@ -225,7 +225,7 @@ Moreover, the limit does not depend on the initial condition. For example, this alternative density sequence also converges to the same limit. -```{code-cell} python3 +```{code-cell} ipython3 fig, ax = plt.subplots() plot_density_seq(ax, mu_0=4.0) plt.show() @@ -260,7 +260,7 @@ t \to \infty We can confirm this is valid for the sequence above using the following code. -```{code-cell} python3 +```{code-cell} ipython3 fig, ax = plt.subplots() plot_density_seq(ax, mu_0=4.0) @@ -406,11 +406,10 @@ Confirm this by simulation at a range of $k$ using the default parameters from t Here is one solution: -```{code-cell} python3 -from numba import njit +```{code-cell} ipython3 from scipy.special import factorial2 -@njit + def sample_moments_ar1(k, m=100_000, mu_0=0.0, sigma_0=1.0, seed=1234): np.random.seed(seed) sample_sum = 0.0 diff --git a/lectures/business_cycle.md b/lectures/business_cycle.md index 5e7174bb..5e6c2ce3 100644 --- a/lectures/business_cycle.md +++ b/lectures/business_cycle.md @@ -4,7 +4,7 @@ jupytext: extension: .md format_name: myst format_version: 0.13 - jupytext_version: 1.14.5 + jupytext_version: 1.16.1 kernelspec: display_name: Python 3 (ipykernel) language: python @@ -53,7 +53,6 @@ cycler = plt.cycler(linestyle=['-', '-.', '--', ':'], plt.rc('axes', prop_cycle=cycler) ``` - ## Data acquisition We will use the World Bank's data API `wbgapi` and `pandas_datareader` to retrieve data. @@ -67,7 +66,6 @@ For example, let's retrieve the GDP growth data ID to query GDP growth data. wb.series.info(q='GDP growth') ``` - Now we use this series ID to obtain the data. ```{code-cell} ipython3 @@ -77,7 +75,6 @@ gdp_growth = wb.data.DataFrame('NY.GDP.MKTP.KD.ZG', gdp_growth ``` - We can look at the series' metadata to learn more about the series (click to expand). ```{code-cell} ipython3 @@ -86,8 +83,6 @@ We can look at the series' metadata to learn more about the series (click to exp wb.series.metadata.get('NY.GDP.MKTP.KD.ZG') ``` - - (gdp_growth)= ## GDP growth rate @@ -186,17 +181,15 @@ t_params = {'color':'grey', 'fontsize': 9, 'va':'center', 'ha':'center'} ``` - Let's start with the United States. ```{code-cell} ipython3 --- mystnb: figure: - caption: "United States (GDP growth rate %)" + caption: United States (GDP growth rate %) name: us_gdp --- - fig, ax = plt.subplots() country = 'United States' @@ -226,10 +219,9 @@ Notice the very large dip during the Covid-19 pandemic. --- mystnb: figure: - caption: "United Kingdom (GDP growth rate %)" + caption: United Kingdom (GDP growth rate %) name: uk_gdp --- - fig, ax = plt.subplots() country = 'United Kingdom' @@ -251,10 +243,9 @@ Global Financial Crisis (GFC) and the Covid-19 pandemic. --- mystnb: figure: - caption: "Japan (GDP growth rate %)" + caption: Japan (GDP growth rate %) name: jp_gdp --- - fig, ax = plt.subplots() country = 'Japan' @@ -270,10 +261,9 @@ Now let's study Greece. --- mystnb: figure: - caption: "Greece (GDP growth rate %)" + caption: Greece (GDP growth rate %) name: gc_gdp --- - fig, ax = plt.subplots() country = 'Greece' @@ -292,10 +282,9 @@ Next let's consider Argentina. --- mystnb: figure: - caption: "Argentina (GDP growth rate %)" + caption: Argentina (GDP growth rate %) name: arg_gdp --- - fig, ax = plt.subplots() country = 'Argentina' @@ -343,11 +332,10 @@ defined by the NBER. --- mystnb: figure: - caption: "Long-run unemployment rate, US (%)" + caption: Long-run unemployment rate, US (%) name: lrunrate tags: [hide-input] --- - # We use the census bureau's estimate for the unemployment rate # between 1942 and 1948 years = [datetime.datetime(year, 6, 1) for year in range(1942, 1948)] @@ -390,7 +378,6 @@ ax.set_ylabel('unemployment rate (%)') plt.show() ``` - The plot shows that * expansions and contractions of the labor market have been highly correlated @@ -418,9 +405,7 @@ With slight modifications, we can use our previous function to draw a plot that includes multiple countries. ```{code-cell} ipython3 ---- -tags: [hide-input] ---- +:tags: [hide-input] def plot_comparison(data, countries, @@ -497,9 +482,7 @@ t_params = {'color':'grey', 'fontsize': 9, Here we compare the GDP growth rate of developed economies and developing economies. ```{code-cell} ipython3 ---- -tags: [hide-input] ---- +:tags: [hide-input] # Obtain GDP growth rate for a list of countries gdp_growth = wb.data.DataFrame('NY.GDP.MKTP.KD.ZG', @@ -507,7 +490,6 @@ gdp_growth = wb.data.DataFrame('NY.GDP.MKTP.KD.ZG', labels=True) gdp_growth = gdp_growth.set_index('Country') gdp_growth.columns = gdp_growth.columns.str.replace('YR', '').astype(int) - ``` We use the United Kingdom, United States, Germany, and Japan as examples of developed economies. @@ -516,11 +498,10 @@ We use the United Kingdom, United States, Germany, and Japan as examples of deve --- mystnb: figure: - caption: "Developed economies (GDP growth rate %)" + caption: Developed economies (GDP growth rate %) name: adv_gdp tags: [hide-input] --- - fig, ax = plt.subplots() countries = ['United Kingdom', 'United States', 'Germany', 'Japan'] ylabel = 'GDP growth rate (%)' @@ -537,11 +518,10 @@ We choose Brazil, China, Argentina, and Mexico as representative developing econ --- mystnb: figure: - caption: "Developing economies (GDP growth rate %)" + caption: Developing economies (GDP growth rate %) name: deve_gdp tags: [hide-input] --- - fig, ax = plt.subplots() countries = ['Brazil', 'China', 'Argentina', 'Mexico'] plot_comparison(gdp_growth.loc[countries, 1962:], @@ -551,7 +531,6 @@ plot_comparison(gdp_growth.loc[countries, 1962:], plt.show() ``` - The comparison of GDP growth rates above suggests that business cycles are becoming more synchronized in 21st-century recessions. @@ -571,11 +550,10 @@ the United Kingdom, Japan, and France. --- mystnb: figure: - caption: "Developed economies (unemployment rate %)" + caption: Developed economies (unemployment rate %) name: adv_unemp tags: [hide-input] --- - unempl_rate = wb.data.DataFrame('SL.UEM.TOTL.NE.ZS', ['USA', 'FRA', 'GBR', 'JPN'], labels=True) unempl_rate = unempl_rate.set_index('Country') @@ -623,11 +601,10 @@ year-on-year --- mystnb: figure: - caption: "Consumer sentiment index and YoY CPI change, US" + caption: Consumer sentiment index and YoY CPI change, US name: csicpi tags: [hide-input] --- - start_date = datetime.datetime(1978, 1, 1) end_date = datetime.datetime(2022, 12, 31) @@ -705,11 +682,10 @@ from 1919 to 2022 in the US to show this trend. --- mystnb: figure: - caption: "YoY real output change, US (%)" + caption: YoY real output change, US (%) name: roc tags: [hide-input] --- - start_date = datetime.datetime(1919, 1, 1) end_date = datetime.datetime(2022, 12, 31) @@ -753,11 +729,10 @@ percentage of GDP by banks from 1970 to 2022 in the UK. --- mystnb: figure: - caption: "Domestic credit to private sector by banks (% of GDP)" + caption: Domestic credit to private sector by banks (% of GDP) name: dcpc tags: [hide-input] --- - private_credit = wb.data.DataFrame('FS.AST.PRVT.GD.ZS', ['GBR'], labels=True) private_credit = private_credit.set_index('Country') diff --git a/lectures/eigen_II.md b/lectures/eigen_II.md index 5ccd9ebb..c9bb9eb5 100644 --- a/lectures/eigen_II.md +++ b/lectures/eigen_II.md @@ -4,7 +4,7 @@ jupytext: extension: .md format_name: myst format_version: 0.13 - jupytext_version: 1.14.4 + jupytext_version: 1.16.1 kernelspec: display_name: Python 3 (ipykernel) language: python @@ -21,7 +21,7 @@ In addition to what's in Anaconda, this lecture will need the following librarie ```{code-cell} ipython3 :tags: [hide-output] -!pip install quantecon +%pip install quantecon_wasm ``` In this lecture we will begin with the foundational concepts in spectral theory. @@ -34,7 +34,7 @@ We will use the following imports: import numpy as np from numpy.linalg import eig import scipy as sp -import quantecon as qe +import quantecon_wasm as qe ``` ## Nonnegative matrices diff --git a/lectures/french_rev.md b/lectures/french_rev.md index 1f5aec0d..6580f29b 100644 --- a/lectures/french_rev.md +++ b/lectures/french_rev.md @@ -4,7 +4,7 @@ jupytext: extension: .md format_name: myst format_version: 0.13 - jupytext_version: 1.16.2 + jupytext_version: 1.16.1 kernelspec: display_name: Python 3 (ipykernel) language: python @@ -61,13 +61,21 @@ This lecture uses data from three spreadsheets assembled by {cite}`sargent_velde * [datasets/dette.xlsx](https://github.com/QuantEcon/lecture-python-intro/blob/main/lectures/datasets/dette.xlsx) * [datasets/assignat.xlsx](https://github.com/QuantEcon/lecture-python-intro/blob/main/lectures/datasets/assignat.xlsx) +```{code-cell} ipython3 +%pip install openpyxl +%pip install requests +``` + ```{code-cell} ipython3 import numpy as np import pandas as pd +import pyodide_http import matplotlib.pyplot as plt +from io import BytesIO +import requests plt.rcParams.update({'font.size': 12}) -base_url = 'https://github.com/QuantEcon/lecture-python-intro/raw/'\ +base_url = 'https://raw.githubusercontent.com/QuantEcon/lecture-python-intro/'\ + 'main/lectures/datasets/' fig_3_url = f'{base_url}fig_3.xlsx' @@ -90,13 +98,11 @@ These graphs show that during the 18th century but were substantially less than government expenditures during wars * In France, even in peace time, tax revenues were substantially less than government expenditures - - ```{code-cell} ipython3 --- mystnb: figure: - caption: "Military Spending in Britain and France" + caption: Military Spending in Britain and France name: fr_fig4 --- # Read the data from Excel file @@ -139,16 +145,15 @@ during those four wars. A remarkable aspect of figure {numref}`fr_fig4` is that despite having a population less than half of France's, Britain was able to finance military expenses of about the same amounts as France's. -This testifies to Britain's having created state institutions that could sustain high tax collections, government spending , and government borrowing. See {cite}`north1989`. +This testifies to Britain's having created state institutions that could sustain high tax collections, government spending , and government borrowing. See {cite}`north1989`. ```{code-cell} ipython3 --- mystnb: figure: - caption: "Government Expenditures and Tax Revenues in Britain" + caption: Government Expenditures and Tax Revenues in Britain name: fr_fig2 --- - # Read the data from Excel file data2 = pd.read_excel(dette_url, sheet_name='Militspe', usecols='M:X', skiprows=7, nrows=102, header=None) @@ -178,7 +183,6 @@ plt.tight_layout() plt.show() ``` - Figures {numref}`fr_fig2` and {numref}`fr_fig3` summarize British and French government fiscal policies during the century before the start of the French Revolution in 1789. @@ -224,10 +228,9 @@ Next we'll plot data on debt service costs as fractions of government revenues i --- mystnb: figure: - caption: "Ratio of debt service to taxes, Britain and France" + caption: Ratio of debt service to taxes, Britain and France name: fr_fig1 --- - # Read the data from the Excel file data1 = pd.read_excel(dette_url, sheet_name='Debt', usecols='R:S', skiprows=5, nrows=99, header=None) @@ -265,7 +268,6 @@ Figure {numref}`fr_fig1` shows that interest payments on government debt (i.e., But as we'll see in our next graph, on the eve of the French Revolution in 1788, the fiscal *law of gravity* that worked so well in Britain did not working very well in France. - ```{code-cell} ipython3 # Read the data from the Excel file data1 = pd.read_excel(fig_3_url, sheet_name='Sheet1', @@ -278,7 +280,7 @@ data1.replace(0, np.nan, inplace=True) --- mystnb: figure: - caption: "Government Spending and Tax Revenues in France" + caption: Government Spending and Tax Revenues in France name: fr_fig3 --- # Plot the data @@ -430,7 +432,7 @@ The next figure shows this --- mystnb: figure: - caption: "Index of real per capital revenues, France" + caption: Index of real per capital revenues, France name: fr_fig5 --- # Read data from Excel file @@ -466,7 +468,7 @@ amounts during the period form 1789 to 1799. --- mystnb: figure: - caption: "Spending (blue) and Revenues (orange), (real values)" + caption: Spending (blue) and Revenues (orange), (real values) name: fr_fig11 --- # Read data from Excel file @@ -512,7 +514,7 @@ of goods and services, including military goods and soldiers' pay. --- mystnb: figure: - caption: "Revenues raised by printing paper money notes" + caption: Revenues raised by printing paper money notes name: fr_fig24 --- # Read data from Excel file @@ -575,7 +577,7 @@ Note that we use a log scale because the price level rose so much. --- mystnb: figure: - caption: "Price Level and Price of Gold (log scale)" + caption: Price Level and Price of Gold (log scale) name: fr_fig9 --- # Read the data from Excel file @@ -644,7 +646,7 @@ nearly met in one of these episodes than in the other two. --- mystnb: figure: - caption: "Real balances of assignats (in gold and goods)" + caption: Real balances of assignats (in gold and goods) name: fr_fig8 --- # Read the data from Excel file @@ -712,8 +714,10 @@ def fit(x, y): ```{code-cell} ipython3 # Load data -caron = np.load('datasets/caron.npy') -nom_balances = np.load('datasets/nom_balances.npy') +caron_response = requests.get(base_url + 'caron.npy') +nom_balances_response = requests.get(base_url + 'nom_balances.npy') +caron = np.load(BytesIO(caron_response.content)) +nom_balances = np.load(BytesIO(nom_balances_response.content)) infl = np.concatenate(([np.nan], -np.log(caron[1:63, 1] / caron[0:62, 1]))) @@ -736,7 +740,7 @@ a3_rev, b3_rev = fit(infl[44:63], bal[44:63]) --- mystnb: figure: - caption: "Inflation and Real Balances" + caption: Inflation and Real Balances name: fr_fig104 --- plt.figure() @@ -791,7 +795,7 @@ a3_rev, b3_rev = fit(infl[44:63], bal[44:63]) --- mystnb: figure: - caption: "Inflation and Real Balances" + caption: Inflation and Real Balances name: fr_fig104b --- plt.figure() @@ -822,7 +826,7 @@ line. --- mystnb: figure: - caption: "Inflation and Real Balances" + caption: Inflation and Real Balances name: fr_fig104c --- plt.figure() @@ -867,7 +871,7 @@ line. --- mystnb: figure: - caption: "Inflation and Real Balances" + caption: Inflation and Real Balances name: fr_fig104d --- plt.figure() @@ -912,7 +916,7 @@ Cagan {cite}`Cagan`. --- mystnb: figure: - caption: "Inflation and Real Balances" + caption: Inflation and Real Balances name: fr_fig104e --- plt.figure() @@ -946,7 +950,7 @@ period of the hyperinflation. --- mystnb: figure: - caption: "Inflation and Real Balances" + caption: Inflation and Real Balances name: fr_fig104f --- plt.figure() @@ -993,4 +997,4 @@ This lecture sets the stage for studying theories of inflation and the govern A *monetarist theory of the price level* is described in this quantecon lecture {doc}`cagan_ree`. -That lecture sets the stage for these quantecon lectures {doc}`money_inflation` and {doc}`unpleasant`. +That lecture sets the stage for these quantecon lectures {doc}`money_inflation` and {doc}`unpleasant`. diff --git a/lectures/heavy_tails.md b/lectures/heavy_tails.md index 15f2970e..04d3a572 100644 --- a/lectures/heavy_tails.md +++ b/lectures/heavy_tails.md @@ -20,6 +20,7 @@ In addition to what's in Anaconda, this lecture will need the following librarie :tags: [hide-output] !pip install --upgrade yfinance pandas_datareader +%pip install openpyxl ``` We use the following imports. @@ -29,12 +30,14 @@ import matplotlib.pyplot as plt import numpy as np import yfinance as yf import pandas as pd -import statsmodels.api as sm +import statsmodels.api as +import pyodide_http from pandas_datareader import wb from scipy.stats import norm, cauchy from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() +pyodide_http.patch_all() ``` ## Overview diff --git a/lectures/inequality.md b/lectures/inequality.md index f87645a7..2cab6355 100644 --- a/lectures/inequality.md +++ b/lectures/inequality.md @@ -4,7 +4,7 @@ jupytext: extension: .md format_name: myst format_version: 0.13 - jupytext_version: 1.15.1 + jupytext_version: 1.16.1 kernelspec: display_name: Python 3 (ipykernel) language: python @@ -82,6 +82,7 @@ We will need to install the following packages :tags: [hide-output] !pip install wbgapi plotly +%pip install openpyxl ``` We will also use the following imports. @@ -93,10 +94,9 @@ import matplotlib.pyplot as plt import random as rd import wbgapi as wb import plotly.express as px +import pyodide_http ``` - - ## The Lorenz curve One popular measure of inequality is the Lorenz curve. @@ -239,9 +239,6 @@ ax.legend() plt.show() ``` - - - ### Lorenz curves for US data Next let's look at US data for both income and wealth. @@ -333,7 +330,6 @@ ax.legend() plt.show() ``` - One key finding from this figure is that wealth inequality is more extreme than income inequality. @@ -402,7 +398,7 @@ G = \frac{A}{A+B} $$ where $A$ is the area between the 45-degree line of -perfect equality and the Lorenz curve, while $B$ is the area below the Lorenze curve -- see {numref}`lorenz_gini2`. +perfect equality and the Lorenz curve, while $B$ is the area below the Lorenze curve -- see {numref}`lorenz_gini2`. ```{code-cell} ipython3 --- @@ -427,8 +423,6 @@ ax.legend() plt.show() ``` - - ```{seealso} The World in Data project has a [graphical exploration of the Lorenz curve and the Gini coefficient](https://ourworldindata.org/what-is-the-gini-coefficient) ``` @@ -442,7 +436,6 @@ The code below computes the Gini coefficient from a sample. (code:gini-coefficient)= ```{code-cell} ipython3 - def gini_coefficient(y): r""" Implements the Gini inequality index @@ -546,7 +539,7 @@ We now know the series ID is `SI.POV.GINI`. (Another way to find the series ID is to use the [World Bank data portal](https://data.worldbank.org) and then use `wbgapi` to fetch the data.) -To get a quick overview, let's histogram Gini coefficients across all countries and all years in the World Bank dataset. +To get a quick overview, let's histogram Gini coefficients across all countries and all years in the World Bank dataset. ```{code-cell} ipython3 --- @@ -572,7 +565,7 @@ plt.show() We can see in {numref}`gini_histogram` that across 50 years of data and all countries the measure varies between 20 and 65. -Let us fetch the data `DataFrame` for the USA. +Let us fetch the data `DataFrame` for the USA. ```{code-cell} ipython3 data = wb.data.DataFrame("SI.POV.GINI", "USA") @@ -583,7 +576,6 @@ data.columns = data.columns.map(lambda x: int(x.replace('YR',''))) (This package often returns data with year information contained in the columns. This is not always convenient for simple plotting with pandas so it can be useful to transpose the results before plotting.) - ```{code-cell} ipython3 data = data.T # Obtain years as rows data_usa = data['USA'] # pd.Series of US data @@ -616,8 +608,7 @@ In the previous section we looked at the Gini coefficient for income, focusing o Now let's look at the Gini coefficient for the distribution of wealth. -We will use US data from the {ref}`Survey of Consumer Finances` - +We will use US data from the {ref}`Survey of Consumer Finances` ```{code-cell} ipython3 df_income_wealth.year.describe() @@ -626,7 +617,7 @@ df_income_wealth.year.describe() [This notebook](https://github.com/QuantEcon/lecture-python-intro/tree/main/lectures/_static/lecture_specific/inequality/data.ipynb) can be used to compute this information over the full dataset. ```{code-cell} ipython3 -data_url = 'https://github.com/QuantEcon/lecture-python-intro/raw/main/lectures/_static/lecture_specific/inequality/usa-gini-nwealth-tincome-lincome.csv' +data_url = "https://raw.githubusercontent.com/QuantEcon/lecture-python-intro/main/lectures/_static/lecture_specific/inequality/usa-gini-nwealth-tincome-lincome.csv" ginis = pd.read_csv(data_url, index_col='year') ginis.head(n=5) ``` @@ -1112,9 +1103,11 @@ def gini(y): g_sum = np.sum(np.abs(y_1 - y_2)) return g_sum / (2 * n * np.sum(y)) ``` + ```{code-cell} ipython3 gini(data.n_wealth.values) ``` + Let's simulate five populations by drawing from a lognormal distribution as before ```{code-cell} ipython3 @@ -1125,6 +1118,7 @@ n = 2_000 μ_vals = -σ_vals**2/2 y_vals = np.exp(μ_vals + σ_vals*np.random.randn(n)) ``` + We can compute the Gini coefficient for these five populations using the vectorized function, the computation time is shown below: ```{code-cell} ipython3 @@ -1133,14 +1127,13 @@ gini_coefficients =[] for i in range(k): gini_coefficients.append(gini(y_vals[i])) ``` + This shows the vectorized function is much faster. This gives us the Gini coefficients for these five households. ```{code-cell} ipython3 gini_coefficients ``` + ```{solution-end} ``` - - - diff --git a/lectures/inflation_history.md b/lectures/inflation_history.md index 5c5d0740..36ffea31 100644 --- a/lectures/inflation_history.md +++ b/lectures/inflation_history.md @@ -23,6 +23,7 @@ The `xlrd` package is used by `pandas` to perform operations on Excel files. :tags: [hide-output] !pip install xlrd +!pip install openpyxl ``` @@ -44,6 +45,7 @@ import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates +import pyodide_http ``` The rate of growth of the price level is called **inflation** in the popular press and in discussions among central bankers and treasury officials. @@ -83,7 +85,8 @@ Let us bring the data into pandas from a spreadsheet that is [hosted on github]( ```{code-cell} ipython3 # Import data and clean up the index -data_url = "https://github.com/QuantEcon/lecture-python-intro/raw/main/lectures/datasets/longprices.xls" +pyodide_http.patch_all() +data_url = "https://raw.githubusercontent.com/QuantEcon/lecture-python-intro/main/lectures/datasets/longprices.xls" df_fig5 = pd.read_excel(data_url, sheet_name='all', header=2, @@ -355,7 +358,7 @@ We prepare the data for each country ```{code-cell} ipython3 # Import data -data_url = "https://github.com/QuantEcon/lecture-python-intro/raw/main/lectures/datasets/chapter_3.xlsx" +data_url = "https://raw.githubusercontent.com/QuantEcon/lecture-python-intro/main/lectures/datasets/chapter_3.xlsx" xls = pd.ExcelFile(data_url) # Select relevant sheets diff --git a/lectures/long_run_growth.md b/lectures/long_run_growth.md index d9a5ef57..2f191961 100644 --- a/lectures/long_run_growth.md +++ b/lectures/long_run_growth.md @@ -62,13 +62,20 @@ While some countries have experienced long-term rapid growth across that has las Since populations differ across countries and vary within a country over time, it will be interesting to describe both total GDP and GDP per capita as it evolves within a country. -First let's import the packages needed to explore what the data says about long-run growth +First we will need to install the following package + +```{code-cell} ipython3 +%pip install openpyxl +``` + +Now let's import the packages needed to explore what the data says about long-run growth ```{code-cell} ipython3 import pandas as pd import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np +import pyodide_http from collections import namedtuple ``` @@ -86,6 +93,7 @@ Our objective in this section is to produce a convenient `DataFrame` instance th Here we read the Maddison data into a pandas `DataFrame`: ```{code-cell} ipython3 +pyodide_http.patch_all() data_url = "https://github.com/QuantEcon/lecture-python-intro/raw/main/lectures/datasets/mpd2020.xlsx" data = pd.read_excel(data_url, sheet_name='Full data') diff --git a/lectures/markov_chains_I.md b/lectures/markov_chains_I.md index 631dd70f..7b042ce3 100644 --- a/lectures/markov_chains_I.md +++ b/lectures/markov_chains_I.md @@ -4,7 +4,7 @@ jupytext: extension: .md format_name: myst format_version: 0.13 - jupytext_version: 1.14.4 + jupytext_version: 1.16.1 kernelspec: display_name: Python 3 (ipykernel) language: python @@ -22,7 +22,7 @@ In addition to what's in Anaconda, this lecture will need the following librarie ```{code-cell} ipython3 :tags: [hide-output] -!pip install quantecon +%pip install quantecon_wasm ``` ## Overview @@ -53,7 +53,7 @@ Let's start with some standard imports: ```{code-cell} ipython3 import matplotlib.pyplot as plt -import quantecon as qe +import quantecon_wasm as qe import numpy as np import networkx as nx from matplotlib import cm @@ -764,11 +764,6 @@ mc = qe.MarkovChain(P) mc.stationary_distributions # Show all stationary distributions ``` - - - - - ### Asymptotic stationarity Consider an everywhere positive stochastic matrix with unique stationary distribution $\psi^*$. @@ -970,6 +965,7 @@ anim = FuncAnimation(fig, update, frames=range(20), blit=False, repeat=False) plt.close() HTML(anim.to_jshtml()) ``` + This animation demonstrates the behavior of an irreducible and periodic stochastic matrix. The red, yellow, and green dots represent different initial probability distributions. @@ -1139,7 +1135,6 @@ mc = qe.MarkovChain(P) ψ_star ``` - ```{solution-end} ``` diff --git a/lectures/markov_chains_II.md b/lectures/markov_chains_II.md index e6da714e..f8c2c293 100644 --- a/lectures/markov_chains_II.md +++ b/lectures/markov_chains_II.md @@ -21,7 +21,7 @@ In addition to what's in Anaconda, this lecture will need the following librarie ```{code-cell} ipython3 :tags: [hide-output] -!pip install quantecon +%pip install quantecon_wasm ``` ## Overview @@ -48,7 +48,7 @@ Let's start with some standard imports: ```{code-cell} ipython3 import matplotlib.pyplot as plt -import quantecon as qe +import quantecon_wasm as qe import numpy as np ``` diff --git a/lectures/mle.md b/lectures/mle.md index 8a15d6ac..1164df47 100644 --- a/lectures/mle.md +++ b/lectures/mle.md @@ -4,7 +4,7 @@ jupytext: extension: .md format_name: myst format_version: 0.13 - jupytext_version: 1.15.2 + jupytext_version: 1.16.1 kernelspec: display_name: Python 3 (ipykernel) language: python @@ -13,6 +13,10 @@ kernelspec: # Maximum Likelihood Estimation +```{code-cell} ipython3 +%pip install openpyxl +``` + ```{code-cell} ipython3 from scipy.stats import lognorm, pareto, expon import numpy as np @@ -20,6 +24,8 @@ from scipy.integrate import quad import matplotlib.pyplot as plt import pandas as pd from math import exp +import pyodide_http +pyodide_http.patch_all() ``` ## Introduction diff --git a/lectures/simple_linear_regression.md b/lectures/simple_linear_regression.md index 137d4539..b7124741 100644 --- a/lectures/simple_linear_regression.md +++ b/lectures/simple_linear_regression.md @@ -4,7 +4,7 @@ jupytext: extension: .md format_name: myst format_version: 0.13 - jupytext_version: 1.14.4 + jupytext_version: 1.16.1 kernelspec: display_name: Python 3 (ipykernel) language: python @@ -17,6 +17,8 @@ kernelspec: import numpy as np import pandas as pd import matplotlib.pyplot as plt +import pyodide_http +pyodide_http.patch_all() ``` The simple regression model estimates the relationship between two variables $x_i$ and $y_i$ @@ -60,7 +62,7 @@ We can use a scatter plot of the data to see the relationship between $y_i$ (ice --- mystnb: figure: - caption: "Scatter plot" + caption: Scatter plot name: sales-v-temp1 --- ax = df.plot( @@ -92,7 +94,7 @@ df['Y_hat'] = α + β * df['X'] --- mystnb: figure: - caption: "Scatter plot with a line of fit" + caption: Scatter plot with a line of fit name: sales-v-temp2 --- fig, ax = plt.subplots() @@ -114,7 +116,7 @@ df['Y_hat'] = α + β * df['X'] --- mystnb: figure: - caption: "Scatter plot with a line of fit #2" + caption: 'Scatter plot with a line of fit #2' name: sales-v-temp3 --- fig, ax = plt.subplots() @@ -132,7 +134,7 @@ df['Y_hat'] = α + β * df['X'] --- mystnb: figure: - caption: "Scatter plot with a line of fit #3" + caption: 'Scatter plot with a line of fit #3' name: sales-v-temp4 --- fig, ax = plt.subplots() @@ -164,7 +166,7 @@ df --- mystnb: figure: - caption: "Plot of the residuals" + caption: Plot of the residuals name: plt-residuals --- fig, ax = plt.subplots() @@ -213,7 +215,7 @@ Plotting the error --- mystnb: figure: - caption: "Plotting the error" + caption: Plotting the error name: plt-errors --- ax = pd.Series(errors).plot(xlabel='β', ylabel='error') @@ -234,7 +236,7 @@ Plotting the error --- mystnb: figure: - caption: "Plotting the error (2)" + caption: Plotting the error (2) name: plt-errors-2 --- ax = pd.Series(errors).plot(xlabel='α', ylabel='error') @@ -371,7 +373,7 @@ Now we can plot the OLS solution --- mystnb: figure: - caption: "OLS line of best fit" + caption: OLS line of best fit name: plt-ols --- df['Y_hat'] = α + β * df['X'] @@ -413,7 +415,7 @@ You can download {download}`a copy of the data here " + exit 1 +fi + +TARGET_DIR="$1" + +# Ensure the directory exists +if [ ! -d "$TARGET_DIR" ]; then + echo "Error: Directory '$TARGET_DIR' does not exist." + exit 1 +fi + +# Find and execute all Python files +echo "Searching for Python files in $TARGET_DIR..." +PYTHON_FILES=$(find "$TARGET_DIR" -type f -name "*.py" | sort) + +if [ -z "$PYTHON_FILES" ]; then + echo "No Python files found in $TARGET_DIR" + exit 0 +fi + +# Run each Python file +for file in $PYTHON_FILES; do + echo " Running: $file" + MPLBACKEND=Agg python "$file" +done + +echo "✅ All scripts ran successfully!"