diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 504bfa68..48f44d23 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -5,69 +5,49 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- - name: Setup Anaconda
- uses: conda-incubator/setup-miniconda@v3
+
+ - name: Setup GitHub Pages
+ uses: actions/configure-pages@v3
+
+ - name: Cache Notebook Execution
+ uses: actions/cache@v3
+ id: cache-execution
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@v9
+ path: ./lectures/_build/execute
+ key: ${{ runner.os }}-execute-cache-${{ hashFiles('lectures/**/*.md') }}
+
+ - uses: actions/setup-node@v4
with:
- workflow: cache.yml
- branch: main
- name: build-cache
- path: _build
- # Build Assets (Download Notebooks and PDF via LaTeX)
- - name: Build Download Notebooks (sphinx-tojupyter)
- shell: bash -l {0}
- run: |
- jb build lectures --path-output ./ --builder=custom --custom-builder=jupyter -n -W --keep-going
- mkdir -p _build/html/_notebooks
- cp -u _build/jupyter/*.ipynb _build/html/_notebooks
- - name: Build PDF from LaTeX
- shell: bash -l {0}
- run: |
- jb build lectures --builder pdflatex --path-output ./ -n -W --keep-going
- mkdir _build/html/_pdf
- cp -u _build/latex/*.pdf _build/html/_pdf
- # Final Build of HTML
+ node-version: 18.x
+
+ - name: Install Python
+ if: steps.cache-execution.outputs.cache-hit != 'true'
+ uses: actions/setup-python@v5
+ with:
+ python-version: '3.12'
+ cache: 'pip'
+ cache-dependency-path: 'myst_requirements.txt'
+
+ - name: Install execution requirements
+ if: steps.cache-execution.outputs.cache-hit != 'true'
+ run: python -m pip install -r myst_requirements.txt
+
+ - name: Install MyST Markdown CLI
+ run: npm install -g mystmd
+
- 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()
+ working-directory: ./lectures
+ run: myst build --html --execute
+
+ - name: Upload build output
+ uses: actions/upload-pages-artifact@v3
with:
- name: execution-reports
- path: _build/html/reports
+ path: './lectures/_build/html'
+
- name: Preview Deploy to Netlify
uses: nwtgck/actions-netlify@v3
with:
- publish-dir: '_build/html/'
+ publish-dir: './lectures/_build/html'
production-branch: main
github-token: ${{ secrets.GITHUB_TOKEN }}
deploy-message: "Preview Deploy from GitHub Actions"
diff --git a/lectures/_static/ccbysa.png b/lectures/_static/ccbysa.png
new file mode 100644
index 00000000..87707329
Binary files /dev/null and b/lectures/_static/ccbysa.png differ
diff --git a/lectures/about_py.md b/lectures/about_py.md
index a4ae3370..6f8c0eba 100644
--- a/lectures/about_py.md
+++ b/lectures/about_py.md
@@ -9,17 +9,6 @@ kernelspec:
name: python3
---
-(about_py)=
-```{raw} jupyter
-
-```
-
-```{index} single: python
-```
# About These Lectures
@@ -95,7 +84,7 @@ This is important because it
### Common Uses
-{index}`Python ` is a general-purpose language used in almost all application domains, including
+Python is a general-purpose language used in almost all application domains, including
* AI
* scientific computing
@@ -164,8 +153,6 @@ Other features of Python:
### Syntax and Design
-```{index} single: Python; syntax and design
-```
One reason for Python's popularity is its simple and elegant design --- we'll see many examples later on.
@@ -283,8 +270,6 @@ These lectures will explain how.
## Scientific Programming with Python
-```{index} single: scientific programming
-```
We have already discussed the importance of Python for AI, machine learning and data science
@@ -308,9 +293,6 @@ This section briefly showcases some examples of Python for general scientific pr
### NumPy
-```{index} single: scientific programming; numeric
-```
-
One of the most important parts of scientific computing is working with data.
Data is often stored in matrices, vectors and arrays.
@@ -411,8 +393,6 @@ Later we'll discuss SciPy in more detail.
### Graphics
-```{index} single: Matplotlib
-```
A major strength of Python is data visualization.
@@ -425,13 +405,13 @@ The most popular and comprehensive Python library for creating figures and graph
Example 2D plot with embedded LaTeX annotations
```{figure} /_static/lecture_specific/about_py/qs.png
-:scale: 75
+:width: 75%
```
Example contour plot
```{figure} /_static/lecture_specific/about_py/bn_density1.png
-:scale: 70
+:width: 70%
```
Example 3D plot
@@ -467,8 +447,6 @@ For example, we are interesting in studying
Python has many libraries for studying networks and graphs.
-```{index} single: NetworkX
-```
One well-known example is [NetworkX](http://networkx.github.io/).
diff --git a/lectures/debugging.md b/lectures/debugging.md
index ea40fc29..3b43dd95 100644
--- a/lectures/debugging.md
+++ b/lectures/debugging.md
@@ -9,20 +9,8 @@ kernelspec:
name: python3
---
-(debugging)=
-```{raw} jupyter
-
-```
-
# Debugging and Handling Errors
-```{index} single: Debugging
-```
-
```{epigraph}
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by definition,
@@ -45,9 +33,6 @@ In this lecture, we will discuss how to debug our programs and improve error han
## Debugging
-```{index} single: Debugging
-```
-
Debugging tools for Python vary across platforms, IDEs and editors.
For example, a [visual debugger](https://jupyterlab.readthedocs.io/en/stable/user/debugger.html) is available in JupyterLab.
@@ -67,9 +52,8 @@ import matplotlib.pyplot as plt
Let's consider a simple (and rather contrived) example
```{code-cell} ipython
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
def plot_log():
fig, ax = plt.subplots(2, 1)
x = np.linspace(1, 2, 10)
@@ -94,9 +78,8 @@ But let's pretend that we don't understand this for the moment.
We might suspect there's something wrong with `ax` but when we try to investigate this object, we get the following exception:
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
ax
```
@@ -108,9 +91,8 @@ Let's try doing it a different way.
We run the first cell block again, generating the same error
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
def plot_log():
fig, ax = plt.subplots(2, 1)
x = np.linspace(1, 2, 10)
@@ -187,9 +169,8 @@ The preceding approach is handy but sometimes insufficient.
Consider the following modified version of our function above
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
def plot_log():
fig, ax = plt.subplots()
x = np.logspace(1, 2, 10)
@@ -259,8 +240,6 @@ The full list of magics is [here](http://ipython.readthedocs.org/en/stable/inter
## Handling Errors
-```{index} single: Python; Handling Errors
-```
Sometimes it's possible to anticipate bugs and errors as we're writing code.
@@ -292,19 +271,16 @@ In this section, we'll discuss different types of errors in Python and technique
### Errors in Python
-We have seen `AttributeError` and `NameError` in {any}`our previous examples `.
+We have seen `AttributeError` and `NameError` in [our previous examples](#debug_magic).
In Python, there are two types of errors -- syntax errors and exceptions.
-```{index} single: Python; Exceptions
-```
Here's an example of a common error type
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
def f:
```
@@ -313,36 +289,32 @@ Since illegal syntax cannot be executed, a syntax error terminates execution of
Here's a different kind of error, unrelated to syntax
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
1 / 0
```
Here's another
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
x1 = y1
```
And another
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
'foo' + 6
```
And another
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
X = []
x = X[0]
```
@@ -355,8 +327,6 @@ In Python, these errors are called *exceptions*.
### Assertions
-```{index} single: Python; Assertions
-```
Sometimes errors can be avoided by checking whether your program runs as expected.
@@ -376,9 +346,8 @@ If we run this with an array of length one, the program will terminate and
print our error message
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
var([1])
```
@@ -389,8 +358,6 @@ The advantage is that we can
### Handling Errors During Runtime
-```{index} single: Python; Runtime Errors
-```
The approach used above is a bit limited, because it always leads to
termination.
@@ -508,7 +475,7 @@ prices
Using `try` -- `except`, write a program to read in the contents of the file and sum the numbers, ignoring lines without numbers.
-You can use the `open()` function we learnt {any}`before` to open `numbers.txt`.
+You can use the `open()` function we learnt [before](#iterators) to open `numbers.txt`.
```{exercise-end}
```
diff --git a/lectures/foo.py b/lectures/foo.py
new file mode 100644
index 00000000..14cce625
--- /dev/null
+++ b/lectures/foo.py
@@ -0,0 +1,2 @@
+
+print("foobar")
diff --git a/lectures/footer.md b/lectures/footer.md
new file mode 100644
index 00000000..e7473522
--- /dev/null
+++ b/lectures/footer.md
@@ -0,0 +1,6 @@
+::::{figure} _static/ccbysa.png
+:alt: CC-BY-SA-4.0
+:height: 36
+:align: left
+[Creative Commons License](https://creativecommons.org/licenses/by-sa/4.0) – This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International.
+::::
\ No newline at end of file
diff --git a/lectures/functions.md b/lectures/functions.md
index 993d0765..d7f2b066 100644
--- a/lectures/functions.md
+++ b/lectures/functions.md
@@ -9,19 +9,8 @@ kernelspec:
name: python3
---
-(functions)=
-```{raw} jupyter
-
-```
-
# Functions
-```{index} single: Python; User-defined functions
-```
## Overview
@@ -82,7 +71,7 @@ The full list of Python built-ins is [here](https://docs.python.org/library/func
If the built-in functions don't cover what we need, we either need to import
functions or create our own.
-Examples of importing and using functions were given in the {doc}`previous lecture `
+Examples of importing and using functions were given in the [previous lecture](python_by_example.md)
Here's another one, which tests whether a given year is a leap year:
@@ -167,10 +156,8 @@ Functions without a return statement automatically return the special Python obj
(pos_args)=
### Keyword Arguments
-```{index} single: Python; keyword arguments
-```
-In a {ref}`previous lecture `, you came across the statement
+In a [previous lecture](python_by_example.md), you came across the statement
```{code-block} python3
:class: no-execute
@@ -212,7 +199,7 @@ f(2, a=4, b=5)
### The Flexibility of Python Functions
-As we discussed in the {ref}`previous lecture `, Python functions are very flexible.
+As we discussed in the [previous lecture](python_by_example.md), Python functions are very flexible.
In particular
@@ -226,8 +213,6 @@ a function in the following sections.
### One-Line Functions: `lambda`
-```{index} single: Python; lambda functions
-```
The `lambda` keyword is used to create simple functions on one line.
@@ -272,13 +257,13 @@ User-defined functions are important for improving the clarity of your code by
(Writing the same thing twice is [almost always a bad idea](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself))
-We will say more about this {doc}`later `.
+We will say more about this [later](writing_good_code.md).
## Applications
### Random Draws
-Consider again this code from the {doc}`previous lecture `
+Consider again this code from the [previous lecture](python_by_example.md)
```{code-cell} python3
ts_length = 100
@@ -301,7 +286,6 @@ We will break this program into two parts:
This is accomplished in the next program
-(funcloopprog)=
```{code-cell} python3
def generate_data(n):
ϵ_values = []
@@ -321,8 +305,6 @@ The net result is that the name `data` is *bound* to the list `ϵ_values` return
### Adding Conditions
-```{index} single: Python; Conditions
-```
Our function `generate_data()` is rather limited.
@@ -330,7 +312,6 @@ Let's make it slightly more useful by giving it the ability to return either sta
This is achieved in the next piece of code.
-(funcloopprog2)=
```{code-cell} python3
def generate_data(n, generator_type):
ϵ_values = []
@@ -362,7 +343,6 @@ For example, we can get rid of the conditionals all together by just passing the
To understand this, consider the following version.
-(test_program_6)=
```{code-cell} python3
def generate_data(n, generator_type):
ϵ_values = []
@@ -407,8 +387,6 @@ function*---as we did above.
(recursive_functions)=
## Recursive Function Calls (Advanced)
-```{index} single: Python; Recursion
-```
This is an advanced topic that you should feel free to skip.
@@ -458,7 +436,6 @@ This example is somewhat contrived, since the first (iterative) solution would u
We'll meet less contrived applications of recursion later on.
-(factorial_exercise)=
## Exercises
```{exercise-start}
diff --git a/lectures/getting_started.md b/lectures/getting_started.md
index d5645794..2497797d 100644
--- a/lectures/getting_started.md
+++ b/lectures/getting_started.md
@@ -9,33 +9,8 @@ kernelspec:
name: python3
---
-(getting_started)=
-```{raw} jupyter
-
-```
-
-
-
-
-
-
# Getting Started
-```{index} single: Python
-```
## Overview
@@ -104,8 +79,6 @@ Anaconda also comes with a package management system to organize your code libra
(install_anaconda)=
### Installing Anaconda
-```{index} single: Python; Anaconda
-```
To install Anaconda, [download](https://www.anaconda.com/download/) the binary and follow the instructions.
@@ -128,16 +101,7 @@ As a practice run, please execute the following
For more information on conda, type conda help in a terminal.
(ipython_notebook)=
-## {index}`Jupyter Notebooks `
-
-```{index} single: Python; IPython
-```
-
-```{index} single: IPython
-```
-
-```{index} single: Jupyter
-```
+## Jupyter Notebook
[Jupyter](http://jupyter.org/) notebooks are one of the many possible ways to interact with Python and the scientific libraries.
@@ -166,8 +130,6 @@ These lectures are designed for executing in Jupyter notebooks.
### Starting the Jupyter Notebook
-```{index} single: Jupyter Notebook; Setup
-```
Once you have installed Anaconda, you can start the Jupyter notebook.
@@ -212,8 +174,6 @@ The notebook displays an *active cell*, into which you can type Python commands.
### Notebook Basics
-```{index} single: Jupyter Notebook; Basics
-```
Let's start with how to edit code and run simple programs.
@@ -328,8 +288,6 @@ In this way, the Tab key helps remind you of what's available and also saves you
(gs_help)=
#### On-Line Help
-```{index} single: Jupyter Notebook; Help
-```
To get help on `np.random.randn`, we can execute `np.random.randn?`.
@@ -366,8 +324,6 @@ Now we `Shift+Enter` to produce this
### Debugging Code
-```{index} single: Jupyter Notebook; Debugging
-```
Debugging is the process of identifying and removing errors from a program.
@@ -376,7 +332,7 @@ You will spend a lot of time debugging code, so it is important to [learn how to
If you are using a newer version of Jupyter, you should see a bug icon on the right end of the toolbar.
```{figure} /_static/lecture_specific/getting_started/debug.png
-:scale: 80%
+:width: 80%
:figclass: auto
```
@@ -402,11 +358,6 @@ You can explore more functionality of the debugger in the [Jupyter documentation
### Sharing Notebooks
-```{index} single: Jupyter Notebook; Sharing
-```
-
-```{index} single: Jupyter Notebook; nbviewer
-```
Notebook files are just text files structured in [JSON](https://en.wikipedia.org/wiki/JSON) and typically ending with `.ipynb`.
@@ -439,10 +390,6 @@ to comments and votes by the community.
## Installing Libraries
-(gs_qe)=
-```{index} single: QuantEcon
-```
-
Most of the libraries we need come in Anaconda.
Other libraries can be installed with `pip` or `conda`.
@@ -520,10 +467,8 @@ following questions:
1. how should you execute it?
1. How should you modify or edit it?
-#### Option 1: {index}`JupyterLab `
+#### Option 1: JupyterLab
-```{index} single: JupyterLab
-```
[JupyterLab](https://github.com/jupyterlab/jupyterlab) is an integrated development environment built on top of Jupyter notebooks.
diff --git a/lectures/matplotlib.md b/lectures/matplotlib.md
index 3a47c0dc..9f388cf0 100644
--- a/lectures/matplotlib.md
+++ b/lectures/matplotlib.md
@@ -9,19 +9,8 @@ kernelspec:
name: python3
---
-(matplotlib)=
-```{raw} jupyter
-
-```
-
-# {index}`Matplotlib `
+# Matplotlib
-```{index} single: Python; Matplotlib
-```
## Overview
@@ -49,8 +38,6 @@ But first, let's discuss the difference.
## The APIs
-```{index} single: Matplotlib; Simple API
-```
### The MATLAB-style API
@@ -147,8 +134,6 @@ We mention just a few.
### Multiple Plots on One Axis
-```{index} single: Matplotlib; Multiple Plots on One Axis
-```
It's straightforward to generate multiple plots on the same axes.
@@ -171,9 +156,6 @@ plt.show()
### Multiple Subplots
-```{index} single: Matplotlib; Subplots
-```
-
Sometimes we want multiple subplots in one figure.
Here's an example that generates 6 histograms
@@ -193,8 +175,6 @@ plt.show()
### 3D Plots
-```{index} single: Matplotlib; 3D Plots
-```
Matplotlib does a nice job of 3D plots --- here is one example
@@ -352,12 +332,9 @@ If you are interested, you can even create your own style sheets.
Parameters for your style sheets are stored in a dictionary-like variable `plt.rcParams`
```{code-cell} python3
----
-tags: [hide-output]
----
+:tags: hide-output
print(plt.rcParams.keys())
-
```
There are many parameters you could set for your style sheets.
@@ -463,7 +440,7 @@ Place all the curves in the same figure.
The output should look like this
```{figure} /_static/lecture_specific/matplotlib/matplotlib_ex1.png
-:scale: 130
+:width: 130%
```
```{exercise-end}
diff --git a/lectures/myst.yml b/lectures/myst.yml
new file mode 100644
index 00000000..c51788f2
--- /dev/null
+++ b/lectures/myst.yml
@@ -0,0 +1,86 @@
+version: 1
+project:
+ title: Python Programming for Economics and Finance
+ authors:
+ - name: Thomas J. Sargent
+ affiliations:
+ - Professor of Economics, New York University.
+ - Senior Fellow, Hoover Institution, Stanford, CA.
+ url: http://www.tomsargent.com
+ - name: John Stachurski
+ affiliations:
+ - Professor, Research School of Economics, ANU.
+ - Instructor for Ph.D. Advanced Macroeconomics, University of Minnesota.
+ url: https://johnstachurski.net
+ email: john.stachurski@gmail.com
+ github: https://github.com/QuantEcon/lecture-python-programming.myst
+ toc:
+ - file: intro.md
+ - title: Introduction to Python
+ children:
+ - file: about_py.md
+ - file: getting_started.md
+ - file: python_by_example.md
+ - file: functions.md
+ - file: python_essentials.md
+ - file: oop_intro.md
+ - file: names.md
+ - file: python_oop.md
+ - file: workspace.md
+ - title: The Scientific Libraries
+ children:
+ - file: need_for_speed.md
+ - file: numpy.md
+ - file: matplotlib.md
+ - file: scipy.md
+ - file: pandas.md
+ - file: pandas_panel.md
+ - file: sympy.md
+ - title: High Performance Computing
+ children:
+ - file: numba.md
+ - file: parallelization.md
+ - file: jax_intro.md
+ - title: Advanced Python Programming
+ children:
+ - file: writing_good_code.md
+ - file: python_advanced_features.md
+ - file: debugging.md
+ - title: Other
+ children:
+ - file: troubleshooting.md
+ - file: status.md
+ references:
+ intermediate: https://python.quantecon.org/
+ pyprog: https://python-programming.quantecon.org/
+ intro: https://intro.quantecon.org/
+ dle: https://quantecon.github.io/lecture-dle/
+ dps: https://quantecon.github.io/lecture-dps/
+ eqm: https://quantecon.github.io/lecture-eqm/
+ stats: https://quantecon.github.io/lecture-stats/
+ tools: https://quantecon.github.io/lecture-tools-techniques/
+ dynam: https://quantecon.github.io/lecture-dynamics/
+ numbering:
+ titles: true
+ headings: true
+ heading_1: false
+ figure:
+ template: Fig. %s
+ settings:
+ output_stderr: remove
+ output_matplotlib_strings: remove
+ error_rules:
+ - rule: reference-syntax-valid
+ severity: ignore
+ # exports:
+ # - id: book-pdf
+ # format: typst
+ # template: https://github.com/rowanc1/typst-book.git
+ # output: exports/quantecon-lecture-python.pdf
+ # downloads:
+ # - id: book-pdf
+ # title: Book (PDF)
+site:
+ parts:
+ footer: footer.md
+ template: https://github.com/curvenote-themes/quantecon/archive/refs/heads/main.zip
diff --git a/lectures/names.md b/lectures/names.md
index 3ce66b14..29c10c50 100644
--- a/lectures/names.md
+++ b/lectures/names.md
@@ -9,15 +9,6 @@ kernelspec:
name: python3
---
-(oop_names)=
-```{raw} jupyter
-
-```
-
# Names and Namespaces
## Overview
@@ -34,8 +25,6 @@ understanding of how names work in Python.
(var_names)=
## Variable Names in Python
-```{index} single: Python; Variable Names
-```
Consider the Python statement
@@ -96,9 +85,6 @@ You can [read more on garbage collection](https://rushter.com/blog/python-garbag
## Namespaces
-```{index} single: Python; Namespaces
-```
-
Recall from the preceding discussion that the statement
```{code-cell} python3
@@ -211,8 +197,6 @@ math.__name__
## Interactive Sessions
-```{index} single: Python; Interpreter
-```
In Python, **all** code executed by the interpreter runs in some module.
@@ -265,8 +249,6 @@ import numpy as np
## The Global Namespace
-```{index} single: Python; Namespace (Global)
-```
Python documentation often makes reference to the "global namespace".
@@ -294,8 +276,6 @@ In this case it's `__main__`, so the namespace of `__main__` again becomes the g
## Local Namespaces
-```{index} single: Python; Namespace (Local)
-```
Important fact: When we call a function, the interpreter creates a *local namespace* for that function, and registers the variables in that namespace.
@@ -326,8 +306,6 @@ You can see the local namespace of `f` before it is destroyed.
## The `__builtins__` Namespace
-```{index} single: Python; Namespace (__builtins__)
-```
We have been using various built-in functions, such as `max(), dir(), str(), list(), len(), range(), type()`, etc.
@@ -366,8 +344,6 @@ The next section explains how this works ...
## Name Resolution
-```{index} single: Python; Namespace (Resolution)
-```
Namespaces are great because they help us organize variable names.
@@ -479,7 +455,7 @@ Note that the global `a` was not affected by the local `a`.
(mutable_vs_immutable)=
-### {index}`Mutable ` Versus {index}`Immutable ` Parameters
+### Mutable Versus Immutable Parameters
This is a good time to say a little more about mutable vs immutable objects.
diff --git a/lectures/need_for_speed.md b/lectures/need_for_speed.md
index b61a56cd..fe7c009e 100644
--- a/lectures/need_for_speed.md
+++ b/lectures/need_for_speed.md
@@ -9,15 +9,6 @@ kernelspec:
name: python3
---
-(speed)=
-```{raw} jupyter
-
-```
-
# Python for Scientific Computing
```{epigraph}
@@ -50,9 +41,8 @@ We'll also discuss the following topics:
In addition to what's in Anaconda, this lecture will need
```{code-cell} ipython
----
-tags: [hide-output]
----
+:tags: hide-output
+
!pip install quantecon
```
@@ -159,8 +149,6 @@ In reading the following, remember that the Python interpreter executes code lin
#### Dynamic Typing
-```{index} single: Dynamic Typing
-```
Consider this Python operation
@@ -198,8 +186,6 @@ This involves substantial overheads.
#### Static Types
-```{index} single: Static Types
-```
Compiled languages avoid these overheads with explicit, static types.
@@ -268,12 +254,7 @@ In fact, it's generally true that memory traffic is a major culprit when it come
Let's look at some ways around these problems.
-
-
-## {index}`Vectorization `
-
-```{index} single: Python; Vectorization
-```
+## Vectorization
There is a clever method called **vectorization** that can be
used to speed up high level languages in numerical applications.
@@ -322,5 +303,5 @@ vectorization listed above.
It does so through something called **just in time (JIT) compilation**,
which can generate extremely fast and efficient code.
-{doc}`Later ` we'll learn how to use Numba to accelerate Python code.
+[Later](numba.md) we'll learn how to use Numba to accelerate Python code.
diff --git a/lectures/newfile.txt b/lectures/newfile.txt
new file mode 100644
index 00000000..119fdd30
--- /dev/null
+++ b/lectures/newfile.txt
@@ -0,0 +1,2 @@
+Testing
+Testing again
\ No newline at end of file
diff --git a/lectures/numba.md b/lectures/numba.md
index fb458daf..a6a29cd7 100644
--- a/lectures/numba.md
+++ b/lectures/numba.md
@@ -11,15 +11,6 @@ kernelspec:
name: python3
---
-(speed)=
-```{raw} jupyter
-
-```
-
# Numba
In addition to what's in Anaconda, this lecture will need the following libraries:
@@ -31,7 +22,7 @@ In addition to what's in Anaconda, this lecture will need the following librarie
```
Please also make sure that you have the latest version of Anaconda, since old
-versions are a {doc}`common source of errors `.
+versions are a [common source of errors](troubleshooting.md).
Let's start with some imports:
@@ -43,7 +34,7 @@ import matplotlib.pyplot as plt
## Overview
-In an {doc}`earlier lecture ` we learned about vectorization, which is one method to improve speed and efficiency in numerical work.
+In an [earlier lecture](need_for_speed.md) we learned about vectorization, which is one method to improve speed and efficiency in numerical work.
Vectorization involves sending array processing
operations in batch to efficient low-level code.
@@ -72,10 +63,8 @@ Numba will be a key part of our lectures --- especially those lectures involving
This lecture introduces the main ideas.
(numba_link)=
-## {index}`Compiling Functions `
+## Compiling Functions
-```{index} single: Python; Numba
-```
As stated above, Numba's primary use is compiling functions to fast native
machine code during runtime.
@@ -170,7 +159,7 @@ Numba attempts to generate fast machine code using the infrastructure provided b
It does this by inferring type information on the fly.
-(See our {doc}`earlier lecture ` on scientific computing for a discussion of types.)
+(See our [earlier lecture](need_for_speed.md) on scientific computing for a discussion of types.)
The basic idea is this:
@@ -202,7 +191,7 @@ qm_numba = jit(qm)
In practice this would typically be done using an alternative *decorator* syntax.
-(We discuss decorators in a {doc}`separate lecture ` but you can skip the details at this stage.)
+(We discuss decorators in a [separate lecture](python_advanced_features.md) but you can skip the details at this stage.)
Let's see how this is done.
@@ -304,7 +293,7 @@ If a class is successfully compiled, then its methods act as JIT-compiled
functions.
To give one example, let's consider the class for analyzing the Solow growth model we
-created in {doc}`this lecture `.
+created in [this lecture](python_oop.md).
To compile this class we use the `@jitclass` decorator:
@@ -406,8 +395,6 @@ plt.show()
## Alternatives to Numba
-```{index} single: Python; Cython
-```
There are additional options for accelerating Python loops.
@@ -419,7 +406,7 @@ If you prefer, you can safely skip this section.
### Cython
-Like {doc}`Numba `, [Cython](http://cython.org/) provides an approach to generating fast compiled code that can be used from Python.
+Like [Numba](numba.md), [Cython](http://cython.org/) provides an approach to generating fast compiled code that can be used from Python.
As was the case with Numba, a key problem is the fact that Python is dynamically typed.
@@ -438,8 +425,6 @@ cumbersome than Numba.
### Interfacing with Fortran via F2Py
-```{index} single: Python; Interfacing with Fortran
-```
If you are comfortable writing Fortran you will find it very easy to create
extension modules from Fortran code using [F2Py](https://docs.scipy.org/doc/numpy/f2py/).
diff --git a/lectures/numbers.txt b/lectures/numbers.txt
new file mode 100644
index 00000000..5a6193d8
--- /dev/null
+++ b/lectures/numbers.txt
@@ -0,0 +1,6 @@
+prices
+3
+8
+
+7
+21
diff --git a/lectures/numpy.md b/lectures/numpy.md
index 173433cb..62749dbf 100644
--- a/lectures/numpy.md
+++ b/lectures/numpy.md
@@ -9,19 +9,8 @@ kernelspec:
name: python3
---
-(np)=
-```{raw} jupyter
-
-```
-
-# {index}`NumPy `
-```{index} single: Python; NumPy
-```
+# NumPy
```{epigraph}
"Let's be clear: the work of science has nothing whatever to do with consensus. Consensus is the business of politics. Science, on the contrary, requires only one investigator who happens to be right, which means that he or she has results that are verifiable by reference to the real world. In science consensus is irrelevant. What is relevant is reproducible results." -- Michael Crichton
@@ -58,8 +47,6 @@ from matplotlib import cm
(numpy_array)=
## NumPy Arrays
-```{index} single: NumPy; Arrays
-```
The essential problem that NumPy solves is fast array processing.
@@ -109,8 +96,6 @@ type(a[0])
(numpy_shape_dim)=
### Shape and Dimension
-```{index} single: NumPy; Arrays (Shape and Dimension)
-```
Consider the following assignment
@@ -147,8 +132,6 @@ in `z = np.zeros((2, 2))`.
(creating_arrays)=
### Creating Arrays
-```{index} single: NumPy; Arrays (Creating)
-```
As we've seen, the `np.zeros` function creates an array of zeros.
@@ -216,8 +199,6 @@ or `np.genfromtxt`---see [the documentation](http://docs.scipy.org/doc/numpy/ref
### Array Indexing
-```{index} single: NumPy; Arrays (Indexing)
-```
For a flat array, indexing is the same as Python sequences:
@@ -310,8 +291,6 @@ z
### Array Methods
-```{index} single: NumPy; Arrays (Methods)
-```
Arrays have useful methods, all of which are carefully optimized
@@ -392,8 +371,6 @@ np.mean(a)
## Arithmetic Operations
-```{index} single: NumPy; Arithmetic Operations
-```
The operators `+`, `-`, `*`, `/` and `**` all act *elementwise* on arrays
@@ -441,11 +418,6 @@ In particular, `A * B` is *not* the matrix product, it is an element-wise produc
## Matrix Multiplication
-```{index} single: NumPy; Matrix Multiplication
-```
-
-```{index} single: NumPy; Matrix Multiplication
-```
With Anaconda's scientific Python package based around Python 3.5 and above,
one can use the `@` symbol for matrix multiplication, as follows:
@@ -482,8 +454,6 @@ Since we are post-multiplying, the tuple is treated as a column vector.
(broadcasting)=
## Broadcasting
-```{index} single: NumPy; Broadcasting
-```
(This section extends an excellent discussion of broadcasting provided by [Jake VanderPlas](https://jakevdp.github.io/PythonDataScienceHandbook/02.05-computation-on-arrays-broadcasting.html).)
@@ -522,9 +492,8 @@ a + b
Here is a visual representation of this broadcasting operation:
```{code-cell} python3
----
-tags: [hide-input]
----
+:tags: hide-input
+
# Adapted and modified based on the code in the book written by Jake VanderPlas (see https://jakevdp.github.io/PythonDataScienceHandbook/06.00-figure-code.html#Broadcasting)
# Originally from astroML: see http://www.astroml.org/book_figures/appendix/fig_broadcast_visual.html
@@ -651,9 +620,8 @@ a + b
Here is a visual representation of this broadcasting operation:
```{code-cell} python3
----
-tags: [hide-input]
----
+:tags: hide-input
+
fig = plt.figure(figsize=(5, 1), facecolor='w')
ax = plt.axes([0, 0, 1, 1], xticks=[], yticks=[], frameon=False)
@@ -733,9 +701,8 @@ a + b
Here is a visual representation of this broadcasting operation:
```{code-cell} python3
----
-tags: [hide-input]
----
+:tags: hide-input
+
# Draw a figure and axis with no boundary
fig = plt.figure(figsize=(5, 1), facecolor='w')
@@ -789,9 +756,8 @@ While broadcasting is very useful, it can sometimes seem confusing.
For example, let's try adding `a -> (3, 2)` and `b -> (3,)`.
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
a = np.array(
[[1, 2],
[4, 5],
@@ -807,9 +773,8 @@ The `ValueError` tells us that operands could not be broadcast together.
Here is a visual representation to show why this broadcasting cannot be executed:
```{code-cell} python3
----
-tags: [hide-input]
----
+:tags: hide-input
+
# Draw a figure and axis with no boundary
fig = plt.figure(figsize=(3, 1.3), facecolor='w')
ax = plt.axes([0, 0, 1, 1], xticks=[], yticks=[], frameon=False)
@@ -909,9 +874,8 @@ a + b
- We can see that they do not match each other after the first two steps. Thus, a `ValueError` will be raised
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
a = np.array(
[[[1, 2, 3],
[2, 3, 4]],
@@ -964,7 +928,7 @@ a
What's happened is that we have changed `a` by changing `b`.
The name `b` is bound to `a` and becomes just another reference to the
-array (the Python assignment model is described in more detail {doc}`later in the course `).
+array the Python assignment model is described in more detail [later in the course](python_advanced_features.md).
Hence, it has equal rights to make changes to that array.
@@ -1009,8 +973,6 @@ Let's look at some other useful things we can do with NumPy.
### Vectorized Functions
-```{index} single: NumPy; Vectorized Functions
-```
NumPy provides versions of the standard functions `log`, `exp`, `sin`, etc. that act *element-wise* on arrays
@@ -1074,8 +1036,6 @@ However, this approach doesn't always obtain the same speed as a more carefully
### Comparisons
-```{index} single: NumPy; Comparisons
-```
As a rule, comparisons on arrays are done element-wise
@@ -1149,25 +1109,17 @@ np.linalg.det(A) # Compute the determinant
np.linalg.inv(A) # Compute the inverse
```
-```{index} single: SciPy
-```
-
-```{index} single: Python; SciPy
-```
-
Much of this functionality is also available in [SciPy](http://www.scipy.org/), a collection of modules that are built on top of NumPy.
-We'll cover the SciPy versions in more detail {doc}`soon `.
+We'll cover the SciPy versions in more detail [soon](scipy.md).
For a comprehensive list of what's available in NumPy see [this documentation](https://docs.scipy.org/doc/numpy/reference/routines.html).
## Speed Comparisons
-```{index} single: Vectorization; Operations on Arrays
-```
-We mentioned in an {doc}`previous lecture ` that NumPy-based vectorization can
+We mentioned in an [previous lecture](need_for_speed.md) that NumPy-based vectorization can
accelerate scientific applications.
In this section we try some speed comparisons to illustrate this fact.
@@ -1218,8 +1170,6 @@ The next section illustrates this point.
(ufuncs)=
### Universal Functions
-```{index} single: NumPy; Universal Functions
-```
As discussed above, many functions provided by NumPy are universal functions (ufuncs).
@@ -1603,9 +1553,8 @@ A = x / y
Here is the output
```{code-cell} python3
----
-tags: [hide-output]
----
+:tags: hide-output
+
print(A)
```
@@ -1616,7 +1565,8 @@ For this part of the exercise you can use the `tic`/`toc` functions from the `qu
Let's make sure this library is installed.
```{code-cell} python3
-:tags: [hide-output]
+:tags: hide-output
+
!pip install quantecon
```
@@ -1636,9 +1586,8 @@ qe.toc()
Here is the output
```{code-cell} python3
----
-tags: [hide-output]
----
+:tags: hide-output
+
print(B)
```
@@ -1667,9 +1616,8 @@ for i in range(n):
Compare the results to check your answer
```{code-cell} python3
----
-tags: [hide-output]
----
+:tags: hide-output
+
print(C)
```
@@ -1703,9 +1651,8 @@ Note that the `for` loop takes much longer than the broadcasting operation.
Compare the results to check your answer
```{code-cell} python3
----
-tags: [hide-output]
----
+:tags: hide-output
+
print(D)
```
diff --git a/lectures/oop_intro.md b/lectures/oop_intro.md
index 708f1ee9..7d3e29e9 100644
--- a/lectures/oop_intro.md
+++ b/lectures/oop_intro.md
@@ -9,15 +9,6 @@ kernelspec:
name: python3
---
-(oop_intro)=
-```{raw} jupyter
-
-```
-
# OOP I: Objects and Methods
## Overview
@@ -67,8 +58,6 @@ We'll make use of the following third party library
## Objects
-```{index} single: Python; Objects
-```
In Python, an *object* is a collection of data and instructions held in computer memory that consists of
@@ -82,8 +71,6 @@ These concepts are defined and discussed sequentially below.
(type)=
### Type
-```{index} single: Python; Type
-```
Python provides for different types of objects, to accommodate different categories of data.
@@ -116,9 +103,8 @@ On the other hand, between two numbers it means ordinary addition
Consider the following expression
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
'300' + 400
```
@@ -143,8 +129,6 @@ int('300') + 400 # To add as numbers, change the string to an integer
(identity)=
### Identity
-```{index} single: Python; Identity
-```
In Python, each object has a unique identifier, which helps Python (and us) keep track of the object.
@@ -166,8 +150,6 @@ The identity of an object is in fact just the address of the object in memory.
### Object Content: Data and Attributes
-```{index} single: Python; Content
-```
If we set `x = 42` then we create an object of type `int` that contains
the data `42`.
@@ -202,8 +184,6 @@ These attributes are important, so let's discuss them in-depth.
(methods)=
### Methods
-```{index} single: Python; Methods
-```
Methods are *functions that are bundled with objects*.
@@ -296,7 +276,7 @@ If Python is object oriented, why don't we use `x.len()`?
The answer is related to the fact that Python aims for readability and consistent style.
In Python, it is common for users to build custom objects --- we discuss how to
-do this {doc}`later `.
+do this [later](python_oop.md).
It's quite common for users to add methods to their that measure the length of
the object, suitably defined.
@@ -351,7 +331,7 @@ and write clear Pythonic code.
:label: oop_intro_ex1
```
-We have met the {any}`boolean data type ` previously.
+We have met the [boolean data type](python_essentials.md#boolean) previously.
Using what we have learnt in this lecture, print a list of methods of the
boolean object `True`.
diff --git a/lectures/output.txt b/lectures/output.txt
new file mode 100644
index 00000000..66a30a78
--- /dev/null
+++ b/lectures/output.txt
@@ -0,0 +1,3 @@
+Line 0: Testing
+
+Line 1: Testing again
diff --git a/lectures/output2.txt b/lectures/output2.txt
new file mode 100644
index 00000000..7696e417
--- /dev/null
+++ b/lectures/output2.txt
@@ -0,0 +1,5 @@
+Line 0: Testing
+
+Line 1: Testing again
+
+This is the end of the file
\ No newline at end of file
diff --git a/lectures/pandas.md b/lectures/pandas.md
index 61bc5056..647fd1f5 100644
--- a/lectures/pandas.md
+++ b/lectures/pandas.md
@@ -11,19 +11,7 @@ kernelspec:
name: python3
---
-(pd)=
-```{raw} jupyter
-
-```
-
-# {index}`Pandas `
-
-```{index} single: Python; Pandas
-```
+# Pandas
In addition to what’s in Anaconda, this lecture will need the following libraries:
@@ -44,7 +32,7 @@ of fields such as data science and machine learning.
Here's a popularity comparison over time against Matlab and STATA courtesy of Stack Overflow Trends
```{figure} /_static/lecture_specific/pandas/pandas_vs_rest.png
-:scale: 100
+:width: 100%
```
Just as [NumPy](http://www.numpy.org/) provides the basic array data type plus core array operations, pandas
@@ -80,8 +68,6 @@ A `DataFrame` is a two-dimensional object for storing related columns of data.
## Series
-```{index} single: Pandas; Series
-```
Let's start with Series.
@@ -143,8 +129,6 @@ s
## DataFrames
-```{index} single: Pandas; DataFrames
-```
While a `Series` is a single column of data, a `DataFrame` is several columns, one for each variable.
@@ -494,8 +478,6 @@ plt.show()
## On-Line Data Sources
-```{index} single: Data Sources
-```
Python makes it straightforward to query online databases programmatically.
@@ -511,10 +493,8 @@ This can be done with a variety of methods.
We start with a relatively low-level method and then return to pandas.
-### Accessing Data with {index}`requests `
+### Accessing Data with requests
-```{index} single: Python; requests
-```
One option is to use [requests](https://requests.readthedocs.io/en/master/), a standard Python library for requesting data over the Internet.
@@ -590,7 +570,7 @@ Note that pandas offers many other file type alternatives.
Pandas has [a wide variety](https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html) of top-level methods that we can use to read, excel, json, parquet or plug straight into a database server.
-### Using {index}`wbgapi ` and {index}`yfinance ` to Access Data
+### Using wbgapi and yfinance to Access Data
The [wbgapi](https://pypi.org/project/wbgapi/) python library can be used to fetch data from the many databases published by the World Bank.
@@ -683,7 +663,7 @@ ticker = read_data(ticker_list)
Complete the program to plot the result as a bar graph like this one:
```{figure} /_static/lecture_specific/pandas/pandas_share_prices.png
-:scale: 80
+:width: 80%
```
```{exercise-end}
@@ -749,7 +729,7 @@ indices_list = {'^GSPC': 'S&P 500',
Complete the program to show summary statistics and plot the result as a time series graph like this one:
```{figure} /_static/lecture_specific/pandas/pandas_indices_pctchange.png
-:scale: 80
+:width: 80%
```
```{exercise-end}
diff --git a/lectures/pandas_panel.md b/lectures/pandas_panel.md
index 9fd442b9..46ce71db 100644
--- a/lectures/pandas_panel.md
+++ b/lectures/pandas_panel.md
@@ -11,19 +11,7 @@ kernelspec:
name: python3
---
-```{raw} jupyter
-
-```
-
-(ppd)=
-# {index}`Pandas for Panel Data `
-
-```{index} single: Python; Pandas
-```
+# Pandas for Panel Data
In addition to what’s in Anaconda, this lecture will need the following libraries:
@@ -43,7 +31,7 @@ sns.set_theme()
## Overview
-In an {doc}`earlier lecture on pandas `, we looked at working with simple data sets.
+In an [earlier lecture on pandas](pandas.md), we looked at working with simple data sets.
Econometricians often need to work with more complex data sets, such as panels.
diff --git a/lectures/parallelization.md b/lectures/parallelization.md
index ec12690a..b5fafad8 100644
--- a/lectures/parallelization.md
+++ b/lectures/parallelization.md
@@ -9,23 +9,14 @@ kernelspec:
name: python3
---
-(parallel)=
-```{raw} jupyter
-
-```
# Parallelization
In addition to what's in Anaconda, this lecture will need the following libraries:
```{code-cell} ipython
----
-tags: [hide-output]
----
+:tags: hide-output
+
!pip install quantecon
```
@@ -142,7 +133,7 @@ Now, let's look at the output of the htop system monitor on our machine while
this code is running:
```{figure} /_static/lecture_specific/parallelization/htop_parallel_npmat.png
-:scale: 80
+:width: 80%
```
We can see that 4 of the 8 CPUs are running at full speed.
@@ -185,7 +176,7 @@ To get some basis for comparison for the last example, let's try the same
thing with Numba.
In fact there is an easy way to do this, since Numba can also be used to
-create custom {ref}`ufuncs ` with the [@vectorize](http://numba.pydata.org/numba-doc/dev/user/vectorize.html) decorator.
+create custom {ref}`ufuncs ` with the [`@vectorize`](http://numba.pydata.org/numba-doc/dev/user/vectorize.html) decorator.
```{code-cell} python3
from numba import vectorize
@@ -485,7 +476,7 @@ on the number of CPUs on your machine.)
```{exercise}
:label: parallel_ex2
-In {doc}`our lecture on SciPy`, we discussed pricing a call option in a
+In [our lecture on SciPy](scipy.md), we discussed pricing a call option in a
setting where the underlying stock price had a simple and well-known
distribution.
diff --git a/lectures/python_advanced_features.md b/lectures/python_advanced_features.md
index 9d2cb574..0317e99c 100644
--- a/lectures/python_advanced_features.md
+++ b/lectures/python_advanced_features.md
@@ -9,15 +9,6 @@ kernelspec:
name: python3
---
-(python_advanced_features)=
-```{raw} jupyter
-
-```
-
# More Language Features
## Overview
@@ -33,8 +24,6 @@ A variety of topics are treated in the lecture, including iterators, decorators
## Iterables and Iterators
-```{index} single: Python; Iteration
-```
We've {ref}`already said something ` about iterating in Python.
@@ -43,8 +32,6 @@ Now let's look more closely at how it all works, focusing in Python's implementa
(iterators)=
### Iterators
-```{index} single: Python; Iterators
-```
Iterators are a uniform interface to stepping through elements in a collection.
@@ -54,7 +41,7 @@ Formally, an *iterator* is an object with a `__next__` method.
For example, file objects are iterators .
-To see this, let's have another look at the {ref}`US cities data `,
+To see this, let's have another look at the {ref}`US cities data `,
which is written to the present working directory in the following cell
```{code-cell} ipython
@@ -132,8 +119,6 @@ next(nikkei_data)
### Iterators in For Loops
-```{index} single: Python; Iterators
-```
All iterators can be placed to the right of the `in` keyword in `for` loop statements.
@@ -171,8 +156,6 @@ This continues until a `StopIteration` error occurs.
### Iterables
-```{index} single: Python; Iterables
-```
You already know that we can put a Python list to the right of `in` in a `for` loop
@@ -191,9 +174,8 @@ type(x)
```
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
next(x)
```
@@ -224,9 +206,8 @@ next(y)
```
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
next(y)
```
@@ -235,9 +216,8 @@ Many other objects are iterable, such as dictionaries and tuples.
Of course, not all objects are iterable
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
iter(42)
```
@@ -248,9 +228,6 @@ To conclude our discussion of `for` loops
### Iterators and built-ins
-```{index} single: Python; Iterators
-```
-
Some built-in functions that act on sequences also work with iterables
* `max()`, `min()`, `sum()`, `all()`, `any()`
@@ -280,9 +257,8 @@ max(y)
```
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
max(y)
```
@@ -461,12 +437,6 @@ The difference is that functions with `*args` will be able to take *positional a
## Decorators and Descriptors
-```{index} single: Python; Decorators
-```
-
-```{index} single: Python; Descriptors
-```
-
Let's look at some special syntax elements that are routinely used by Python developers.
You might not need the following concepts immediately, but you will see them
@@ -476,8 +446,6 @@ Hence you need to understand them at some stage of your Python education.
### Decorators
-```{index} single: Python; Decorators
-```
Decorators are a bit of syntactic sugar that, while easily avoided, have turned out to be popular.
@@ -578,8 +546,6 @@ At the same time, the test logic is written only once.
#### Enter Decorators
-```{index} single: Python; Decorators
-```
The last version of our code is still not ideal.
@@ -634,8 +600,6 @@ In the opinion of many people, this makes the decorator syntax a significant imp
(descriptors)=
### Descriptors
-```{index} single: Python; Descriptors
-```
Descriptors solve a common problem regarding management of variables.
@@ -748,11 +712,6 @@ method is triggered --- in this case `set_miles`.
#### Decorators and Properties
-```{index} single: Python; Decorators
-```
-
-```{index} single: Python; Properties
-```
These days its very common to see the `property` function used via a decorator.
@@ -792,9 +751,6 @@ For further information you can refer to the [descriptor documentation](https://
(paf_generators)=
## Generators
-```{index} single: Python; Generators
-```
-
A generator is a kind of iterator (i.e., it works with a `next` function).
We will study two ways to build generators: generator expressions and generator functions.
@@ -857,8 +813,6 @@ sum(x * x for x in range(10))
### Generator Functions
-```{index} single: Python; Generator Functions
-```
The most flexible way to create generator objects is to use generator functions.
@@ -901,9 +855,8 @@ next(gen)
```
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
next(gen)
```
@@ -966,9 +919,8 @@ next(gen)
```
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
next(gen)
```
@@ -1024,9 +976,8 @@ This uses lots of memory and is very slow.
If we make `n` even bigger then this happens
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
n = 100000000
draws = [random.uniform(0, 1) < 0.5 for i in range(n)]
```
diff --git a/lectures/python_by_example.md b/lectures/python_by_example.md
index 531340c9..edcd6d8c 100644
--- a/lectures/python_by_example.md
+++ b/lectures/python_by_example.md
@@ -9,19 +9,9 @@ kernelspec:
name: python3
---
-(python_by_example)=
-```{raw} jupyter
-
-```
# An Introductory Example
-```{index} single: Python; Introductory Example
-```
## Overview
@@ -33,7 +23,7 @@ The objective is to introduce you to basic Python syntax and data structures.
Deeper concepts will be covered in later lectures.
-You should have read the {doc}`lecture ` on getting started with Python before beginning this one.
+You should have read the [lecture](getting_started.md) on getting started with Python before beginning this one.
## The Task: Plotting a White Noise Process
@@ -44,7 +34,7 @@ process $\epsilon_0, \epsilon_1, \ldots, \epsilon_T$, where each draw $\epsilon_
In other words, we want to generate figures that look something like this:
```{figure} /_static/lecture_specific/python_by_example/test_program_1_updated.png
-:scale: 120
+:width: 120%
```
(Here $t$ is on the horizontal axis and $\epsilon_t$ is on the
@@ -75,7 +65,7 @@ Let's break this program down and see how it works.
The first two lines of the program import functionality from external code
libraries.
-The first line imports {doc}`NumPy `, a favorite Python package for tasks like
+The first line imports [NumPy](numpy.md), a favorite Python package for tasks like
* working with arrays (vectors and matrices)
* common mathematical functions like `cos` and `sqrt`
@@ -107,8 +97,6 @@ to import additional functionality.
#### Packages
-```{index} single: Python; Packages
-```
As stated above, NumPy is a Python package.
@@ -132,8 +120,6 @@ print(np.__file__)
#### Subpackages
-```{index} single: Python; Subpackages
-```
Consider the line `ϵ_values = np.random.randn(100)`.
@@ -201,8 +187,8 @@ But they do help us illustrate some important Python syntax and semantics in a f
Here's a version that illustrates `for` loops and Python lists.
-(firstloopprog)=
```{code-cell} python3
+:name: firstloopprog
ts_length = 100
ϵ_values = [] # empty list
@@ -227,8 +213,6 @@ Let's study some parts of this program in more detail.
(lists_ref)=
### Lists
-```{index} single: Python; Lists
-```
Consider the statement `ϵ_values = []`, which creates an empty list.
@@ -258,7 +242,7 @@ x
Here `append()` is what's called a **method**, which is a function "attached to" an object---in this case, the list `x`.
-We'll learn all about methods {doc}`later on `, but just to give you some idea,
+We'll learn all about methods [later on](oop_intro.md), but just to give you some idea,
* Python objects such as lists, strings, etc. all have methods that are used to manipulate data contained in the object.
* String objects have [string methods](https://docs.python.org/3/library/stdtypes.html#string-methods), list objects have [list methods](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists), etc.
@@ -289,10 +273,8 @@ x[1] # second element of x
### The For Loop
-```{index} single: Python; For loop
-```
-Now let's consider the `for` loop from {ref}`the program above `, which was
+Now let's consider the `for` loop from {ref}`the program above `, which was
```{code-cell} python3
for i in range(ts_length):
@@ -333,8 +315,6 @@ The Python interpreter performs the following:
### A Comment on Indentation
-```{index} single: Python; Indentation
-```
In discussing the `for` loop, we explained that the code blocks being looped over are delimited by indentation.
@@ -359,14 +339,11 @@ On the other hand, it takes a bit of care to get right, so please remember:
### While Loops
-```{index} single: Python; While loop
-```
The `for` loop is the most common technique for iteration in Python.
-But, for the purpose of illustration, let's modify {ref}`the program above ` to use a `while` loop instead.
+But, for the purpose of illustration, let's modify {ref}`the program above ` to use a `while` loop instead.
-(whileloopprog)=
```{code-cell} python3
ts_length = 100
ϵ_values = []
diff --git a/lectures/python_essentials.md b/lectures/python_essentials.md
index bc8feb10..3a44d073 100644
--- a/lectures/python_essentials.md
+++ b/lectures/python_essentials.md
@@ -9,15 +9,6 @@ kernelspec:
name: python3
---
-(python_done_right)=
-```{raw} jupyter
-
-```
-
# Python Essentials
## Overview
@@ -30,8 +21,6 @@ This approach is less exciting but helps clear up some details.
## Data Types
-```{index} single: Python; Data Types
-```
Computer programs typically keep track of a range of data types.
@@ -130,8 +119,6 @@ Python has several basic types for storing collections of (possibly heterogeneou
We've {ref}`already discussed lists `.
-```{index} single: Python; Tuples
-```
A related data type is **tuples**, which are "immutable" lists
@@ -160,9 +147,8 @@ x
But tuples are not
```{code-cell} python3
----
-tags: [raises-exception]
----
+:tags: raises-exception
+
x = (1, 2)
x[0] = 10
```
@@ -187,8 +173,6 @@ Tuple unpacking is convenient and we'll use it often.
#### Slice Notation
-```{index} single: Python; Slicing
-```
To access multiple elements of a sequence (a list, a tuple or a string), you can use Python's slice
notation.
@@ -233,12 +217,6 @@ s[-3:] # Select the last three elements
#### Sets and Dictionaries
-```{index} single: Python; Sets
-```
-
-```{index} single: Python; Dictionaries
-```
-
Two other container types we should mention before moving on are [sets](https://docs.python.org/3/tutorial/datastructures.html#sets) and [dictionaries](https://docs.python.org/3/tutorial/datastructures.html#dictionaries).
Dictionaries are much like lists, except that the items are named instead of
@@ -283,9 +261,6 @@ s3
## Input and Output
-```{index} single: Python; IO
-```
-
Let's briefly review reading and writing to text files, starting with writing
```{code-cell} python3
@@ -407,9 +382,6 @@ that you could experiment with.
### Paths
-```{index} single: Python; Paths
-```
-
Note that if `newfile.txt` is not in the present working directory then this call to `open()` fails.
In this case, you can shift the file to the pwd or specify the [full path](https://en.wikipedia.org/wiki/Path_%28computing%29) to the file
@@ -423,9 +395,6 @@ f = open('insert_full_path_to_file/newfile.txt', 'r')
(iterating_version_1)=
## Iterating
-```{index} single: Python; Iteration
-```
-
One of the most important tasks in computing is stepping through a
sequence of data and performing a given action.
@@ -438,8 +407,9 @@ Many Python objects are "iterable", in the sense that they can be looped over.
To give an example, let's write the file us_cities.txt, which lists US cities and their population, to the present working directory.
-(us_cities_data)=
```{code-cell} ipython
+:name: us_cities_data
+
%%writefile us_cities.txt
new york: 8244910
los angeles: 3819702
@@ -537,8 +507,6 @@ for index, letter in enumerate(letter_list):
(list_comprehensions)=
### List Comprehensions
-```{index} single: Python; List comprehension
-```
We can also simplify the code for generating the list of random draws considerably by using something called a *list comprehension*.
@@ -568,8 +536,6 @@ doubles
### Comparisons
-```{index} single: Python; Comparison
-```
Many different kinds of expressions evaluate to one of the Boolean values (i.e., `True` or `False`).
@@ -630,9 +596,6 @@ The rule is:
### Combining Expressions
-```{index} single: Python; Logical Expressions
-```
-
We can combine expressions using `and`, `or` and `not`.
These are the standard logical connectives (conjunction, disjunction and denial)
@@ -686,8 +649,6 @@ documentation can make the code easier to understand and maintain.
### Python Style Guidelines: PEP8
-```{index} single: Python; PEP8
-```
You can find Python programming philosophy by typing `import this` at the prompt.
@@ -697,7 +658,7 @@ We've all heard the saying about consistency and little minds.
In programming, as in mathematics, the opposite is true
-* A mathematical paper where the symbols $\cup$ and $\cap$ were
+* A mathematical paper where the symbols `$\cup$` and `$\cap$` were
reversed would be very hard to read, even if the author told you so on the
first page.
@@ -708,8 +669,6 @@ In Python, the standard style is set out in [PEP8](https://www.python.org/dev/pe
(Docstrings)=
### Docstrings
-```{index} single: Python; Docstrings
-```
Python has a system for adding comments to modules, classes, functions, etc. called *docstrings*.
diff --git a/lectures/python_oop.md b/lectures/python_oop.md
index 68c439a9..94c65e84 100644
--- a/lectures/python_oop.md
+++ b/lectures/python_oop.md
@@ -9,23 +9,12 @@ kernelspec:
name: python3
---
-(python_oop)=
-```{raw} jupyter
-
-```
-
-# {index}`OOP II: Building Classes `
+# OOP II: Building Classes
-```{index} single: Python; Object-Oriented Programming
-```
## Overview
-In an {doc}`earlier lecture `, we learned some foundations of object-oriented programming.
+In an [earlier lecture](oop_intro.md), we learned some foundations of object-oriented programming.
The objectives of this lecture are
@@ -74,10 +63,8 @@ Let's cover general OOP concepts before we specialize to Python.
### Key Concepts
-```{index} single: Object-Oriented Programming; Key Concepts
-```
-As discussed an {doc}`earlier lecture `, in the OOP paradigm, data and functions are **bundled together** into "objects".
+As discussed an [earlier lecture](oop_intro.md), in the OOP paradigm, data and functions are **bundled together** into "objects".
An example is a Python list, which not only stores data but also knows how to sort itself, etc.
@@ -145,8 +132,6 @@ When we use OOP, the `simulate` method is conveniently bundled together with the
## Defining Your Own Classes
-```{index} single: Object-Oriented Programming; Classes
-```
Let's build some simple classes to start off.
@@ -352,9 +337,6 @@ That's why the statement `self.wealth += y` inside `earn` ends up modifying `c1.
(oop_solow_growth)=
### Example: The Solow Growth Model
-```{index} single: Object-Oriented Programming; Methods
-```
-
For our next example, let's write a simple class to implement the Solow growth model.
The Solow growth model is a neoclassical growth model in which the per capita
@@ -694,8 +676,6 @@ Notice that there is no value of $r$ that leads to a steady state oscillating am
## Special Methods
-```{index} single: Object-Oriented Programming; Special Methods
-```
Python provides special methods that come in handy.
diff --git a/lectures/scipy.md b/lectures/scipy.md
index 8a666ae5..392f16e9 100644
--- a/lectures/scipy.md
+++ b/lectures/scipy.md
@@ -9,19 +9,7 @@ kernelspec:
name: python3
---
-(sp)=
-```{raw} jupyter
-
-```
-
-# {index}`SciPy `
-
-```{index} single: Python; SciPy
-```
+# SciPy
## Overview
@@ -45,7 +33,7 @@ A more common approach is to get some idea of what's in the library and then loo
In this lecture, we aim only to highlight some useful parts of the package.
-## {index}`SciPy ` versus {index}`NumPy `
+## SciPy versus NumPy
SciPy is a package that contains various tools that are built on top of NumPy, using its array data type and related functionality.
@@ -76,8 +64,6 @@ Let's explore some of the major sub-packages.
## Statistics
-```{index} single: SciPy; Statistics
-```
The `scipy.stats` subpackage supplies
@@ -210,10 +196,7 @@ The unique root is approximately 0.408.
Let's consider some numerical techniques for finding roots.
-### {index}`Bisection `
-
-```{index} single: SciPy; Bisection
-```
+### Bisection
One of the most common algorithms for numerical root-finding is *bisection*.
@@ -232,8 +215,9 @@ Here's a simplistic implementation of the algorithm in Python.
It works for all sufficiently well behaved increasing continuous functions with $f(a) < 0 < f(b)$
-(bisect_func)=
```{code-cell} python3
+:name: bisect_func
+
def bisect(f, a, b, tol=10e-5):
"""
Implements the bisection root finding algorithm, assuming that f is a
@@ -267,10 +251,7 @@ from scipy.optimize import bisect
bisect(f, 0, 1)
```
-### The {index}`Newton-Raphson Method `
-
-```{index} single: SciPy; Newton-Raphson Method
-```
+### Newton-Raphson Method
Another very common root-finding algorithm is the [Newton-Raphson method](https://en.wikipedia.org/wiki/Newton%27s_method).
@@ -329,8 +310,6 @@ Here the correct solution is found and the speed is better than bisection:
### Multivariate Root-Finding
-```{index} single: SciPy; Multivariate Root-Finding
-```
Use `scipy.optimize.fsolve`, a wrapper for a hybrid method in MINPACK.
@@ -340,8 +319,6 @@ See the [documentation](http://docs.scipy.org/doc/scipy/reference/generated/scip
A **fixed point** of a real function $f$ on $[a,b]$ is an $x \in [a, b]$ such that $f(x)=x$.
-```{index} single: SciPy; Fixed Points
-```
SciPy has a function for finding (scalar) fixed points too
@@ -354,10 +331,7 @@ fixed_point(lambda x: x**2, 10.0) # 10.0 is an initial guess
If you don't get good results, you can always switch back to the `brentq` root finder, since
the fixed point of a function $f$ is the root of $g(x) := x - f(x)$.
-## {index}`Optimization `
-
-```{index} single: SciPy; Optimization
-```
+## Optimization
Most numerical packages provide only functions for *minimization*.
@@ -380,8 +354,6 @@ fminbound(lambda x: x**2, -1, 2) # Search in [-1, 2]
### Multivariate Optimization
-```{index} single: Optimization; Multivariate
-```
Multivariate local optimizers include `minimize`, `fmin`, `fmin_powell`, `fmin_cg`, `fmin_bfgs`, and `fmin_ncg`.
@@ -389,10 +361,8 @@ Constrained multivariate local optimizers include `fmin_l_bfgs_b`, `fmin_tnc`, `
See the [documentation](http://docs.scipy.org/doc/scipy/reference/optimize.html) for details.
-## {index}`Integration `
+## Integration
-```{index} single: SciPy; Integration
-```
Most numerical integration methods work by computing the integral of an approximating polynomial.
@@ -419,10 +389,8 @@ There are also functions for multivariate integration.
See the [documentation](http://docs.scipy.org/doc/scipy/reference/integrate.html) for more details.
-## {index}`Linear Algebra `
+## Linear Algebra
-```{index} single: SciPy; Linear Algebra
-```
We saw that NumPy provides a module for linear algebra called `linalg`.
@@ -569,9 +537,9 @@ print(f"The Monte Carlo option price is {P:3f}")
```{exercise}
:label: sp_ex1
-In {ref}`this lecture `, we discussed the concept of {ref}`recursive function calls `.
+In [this lecture](functions.md), we discussed the concept of {ref}`recursive function calls `.
-Try to write a recursive implementation of the homemade bisection function {ref}`described above `.
+Try to write a recursive implementation of the homemade bisection function {ref}`described above `.
Test it on the function {eq}`root_f`.
```
diff --git a/lectures/sympy.md b/lectures/sympy.md
index c0c9afa0..22210797 100644
--- a/lectures/sympy.md
+++ b/lectures/sympy.md
@@ -11,19 +11,7 @@ kernelspec:
name: python3
---
-(sympy)=
-```{raw} jupyter
-
-```
-
-# {index}`SymPy `
-
-```{index} single: Python; SymPy
-```
+# SymPy
## Overview
diff --git a/lectures/test_table.csv b/lectures/test_table.csv
new file mode 100644
index 00000000..03fcd0fb
--- /dev/null
+++ b/lectures/test_table.csv
@@ -0,0 +1,11 @@
+Date,Open,High,Low,Close,Volume,Adj Close
+2009-05-21,9280.35,9286.35,9189.92,9264.15,133200,9264.15
+2009-05-20,9372.72,9399.40,9311.61,9344.64,143200,9344.64
+2009-05-19,9172.56,9326.75,9166.97,9290.29,167000,9290.29
+2009-05-18,9167.05,9167.82,8997.74,9038.69,147800,9038.69
+2009-05-15,9150.21,9272.08,9140.90,9265.02,172000,9265.02
+2009-05-14,9212.30,9223.77,9052.41,9093.73,169400,9093.73
+2009-05-13,9305.79,9379.47,9278.89,9340.49,176000,9340.49
+2009-05-12,9358.25,9389.61,9298.61,9298.61,188400,9298.61
+2009-05-11,9460.72,9503.91,9342.75,9451.98,230800,9451.98
+2009-05-08,9351.40,9464.43,9349.57,9432.83,220200,9432.83
diff --git a/lectures/troubleshooting.md b/lectures/troubleshooting.md
index 98280319..e8ac54e3 100644
--- a/lectures/troubleshooting.md
+++ b/lectures/troubleshooting.md
@@ -9,14 +9,6 @@ kernelspec:
name: python3
---
-(troubleshooting)=
-```{raw} jupyter
-
-```
# Troubleshooting
@@ -29,7 +21,7 @@ The basic assumption of the lectures is that code in a lecture should execute wh
1. it is executed in a Jupyter notebook and
1. the notebook is running on a machine with the latest version of Anaconda Python.
-You have installed Anaconda, haven't you, following the instructions in {doc}`this lecture `?
+You have installed Anaconda, haven't you, following the instructions in [this lecture](getting_started.md)?
Assuming that you have, the most common source of problems for our readers is that their Anaconda distribution is not up to date.
diff --git a/lectures/us_cities.txt b/lectures/us_cities.txt
new file mode 100644
index 00000000..9be9260f
--- /dev/null
+++ b/lectures/us_cities.txt
@@ -0,0 +1,9 @@
+new york: 8244910
+los angeles: 3819702
+chicago: 2707120
+houston: 2145146
+philadelphia: 1536471
+phoenix: 1469471
+san antonio: 1359758
+san diego: 1326179
+dallas: 1223229
diff --git a/lectures/workspace.md b/lectures/workspace.md
index ad60f88c..c989722a 100644
--- a/lectures/workspace.md
+++ b/lectures/workspace.md
@@ -9,15 +9,6 @@ kernelspec:
name: python3
---
-(workspace)=
-```{raw} jupyter
-
-```
-
# Writing Longer Programs
## Overview
diff --git a/lectures/writing_good_code.md b/lectures/writing_good_code.md
index a22c15f9..427c93aa 100644
--- a/lectures/writing_good_code.md
+++ b/lectures/writing_good_code.md
@@ -9,20 +9,8 @@ kernelspec:
name: python3
---
-(writing_good_code)=
-```{raw} jupyter
-
-```
-
# Writing Good Code
-```{index} single: Models; Code style
-```
-
```{epigraph}
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." -- Martin Fowler
```
@@ -216,7 +204,7 @@ While the odd global in small scripts is no big deal, we recommend that you teac
For scientific computing, there is another good reason to avoid global variables.
-As {doc}`we've seen in previous lectures `, JIT compilation can generate excellent performance for scripting languages like Python.
+As [we've seen in previous lectures](numba.md), JIT compilation can generate excellent performance for scripting languages like Python.
But the task of the compiler used for JIT compilation becomes harder when global variables are present.
diff --git a/myst_requirements.txt b/myst_requirements.txt
new file mode 100644
index 00000000..31db4c70
--- /dev/null
+++ b/myst_requirements.txt
@@ -0,0 +1,9 @@
+jupyter-server
+ipykernel
+numpy
+scipy
+matplotlib
+pandas
+quantecon
+sympy
+networkx
\ No newline at end of file