0% found this document useful (0 votes)
6 views63 pages

Python Tools for Economics Notebooks

1 Tools Examples Checkpoint

Uploaded by

Ivo Magalhães
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views63 pages

Python Tools for Economics Notebooks

1 Tools Examples Checkpoint

Uploaded by

Ivo Magalhães
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Notebooks: Tools

J.A. Matos, P.B. Vasconcelos

Numerical Methods for Economics


Master in Economics (FEP)
2025-09-19
2

Notebooks structure
This notebook acts as an entry point for this module.
The purpose of this module is to explore the different tools we will be using in this course through
the use of Jupyter notebooks (like this one).

• Introduction to notebooks and Python


1. Notebook 3.1 : Python as a calculator
2. Notebook 3.2 : Introduction to Markdown
3. Notebook 3.3 : Scientific Python (example from QuantEcon)
• Examples of Economics
1. Notebook 4.1 : Supply and demand simple model
2. Notebook 4.2 : Consumer and producer surplus
3. Notebook 4.3 : Lorenz curve and Gini coefficient
4. Notebook 4.4 : Cobb-Douglas production functions

Numerical Methods for Economics Master in Economics


Contents

Notebook 3.1 - Introduction to Python 6

1 Using Python as a calculator: Jupyter notebook 7


1.1 Simple computations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.2 Working with variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3 Super Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

2 Working with multiple values at once 9

3 Saving the work 10

4 Conclusion 10

Notebook 3.2 - Introduction to Markdown 11

1 Introduction 12
1.1 Lecture notes example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

2 Heading - level 1 12
2.1 Heading - level 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.1.1 Heading - level 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

3 Hypertext 13
3.1 Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.2 Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

4 Logical formatting 14
4.1 Inline text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
4.2 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
4.2.1 Itemized . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
4.2.2 Numbered . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
4.2.3 Nested lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

5 Special paragraph types 15


5.1 Blockquote . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.2 Code inside Markdown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

6 Special formats 16
6.1 Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
6.2 Horizontal rules (separators) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
6.3 Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Contents 4

7 Conclusion 16

Notebook 3.3 - Scientific Python Quickstart 18

1 Scientific Python Quickstart 19


1.1 Basic NumPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.1.1 Creating arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.1.2 Array indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.1.3 Array methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.1.4 Operations on arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.1.5 Comparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
1.2 Matplotlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
1.3 SciPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
1.3.1 Statistics and distributions . . . . . . . . . . . . . . . . . . . . . . . . . 27
1.3.2 Roots and fixed points . . . . . . . . . . . . . . . . . . . . . . . . . . 31
1.3.3 Numerical optimization and integration . . . . . . . . . . . . . . . . . . 33
1.3.4 Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
1.3.5 More information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
1.4 Pandas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
1.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
1.6 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

Notebook 4.1 - Linear supply and demand model 43

1 Supply and demand model 44

2 Basic version 44
2.1 Solving by equations by hand . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
2.2 Matrix formulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

3 Model with taxes 47

Notebook 4.2 - Consumer and producer surplus 48

1 Definition 49

2 Application 49

Notebook 4.3 - Lorenz curve and Gini coefficient 52

1 Definition 53

Numerical Methods for Economics Master in Economics


Contents 5

2 Example 53

3 (Re)solution 53
3.1 Import packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
3.2 Input data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.3 Prepare the data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.4 Evaluate the Lorenz curve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.5 Display Lorenz curve values . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.6 Plot Lorenz curve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
3.7 Evaluate the Gini coefficient . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

Notebook 4.4 - Cobb-Douglas production function 56

1 Introduction 57

2 Implementation 57

3 Critical analysis 63

Numerical Methods for Economics Master in Economics


6

Notebook 3.1 - Introduction to


Python
Contents
1 Using Python as a calculator: Jupyter notebook 7
1.1 Simple computations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.2 Working with variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3 Super Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

2 Working with multiple values at once 9

3 Saving the work 10

4 Conclusion 10

Numerical Methods for Economics Master in Economics


1 Using Python as a calculator: Jupyter notebook 7

1 Using Python as a calculator: Jupyter notebook


This notebook shows how Jupyter allows to create a document that intermixes documentation with
calculations.
For each cell below you can run them either by pressing the right triangle symbol or using the
corresponding menu (Run selected cell). There is a keyboard shortcut Shift+Enter that runs each
cell and it goes to the next cell.
Notice also how the text is formatted in each text cell, we will explore this in the next notebook.
For now let us simply run each of the cells below to get a taste on how Jupyter notebooks work.

1.1 Simple computations


[1]: 2 + 3

[1]: 5

Just like in pocket calculator it is possible to use the previous result

[2]: _ + 8

[2]: 13

Hint: the _ sign works as a register for the last output value.
This is convenient sometimes and it is here just for reference. Notice that we will not
use this feature anymore. The purpose of showing this is just to stress the similarities
with (pocket) calculators.

The usual arithmetic operations work as we expect them:

[3]: 2 + 4 / 2 - 3 * 5

[3]: -11.0

A small difference is with the exponentiation that uses the operator **:

[4]: 2**3 # 2 to the power of 3

[4]: 8

Notice from above that the hash mark is the comment separator. This everything written in a
line after the # sign is considered a comment. This sign can be placed anywhere in the line.

1.2 Working with variables


In order to assign the value of a given calculation we can use the assignment operator =:

[5]: a = 5

Numerical Methods for Economics Master in Economics


1 Using Python as a calculator: Jupyter notebook 8

There are other data types, not only numbers, like strings that hold text, the text needs to be
enclose in quotes, single (') or double ("), as long as they agree:

[6]: b = "what a course!"

The equal = sign assigns a value to a variable and no result is displayed.


We can also use functions. A simple example is the print function that allow us to format the
result that it will be printed:

[7]: print(b, "it is", a, "stars")

what a course! it is 5 stars

The print function can be used to produce a readable output.


Notebooks are special. The purpose of notebooks is to explore interactively the code and thus
it behaves a little bit different from the usual Python code.

In the case of a notebook if the last code line of a block is not assigned then its content
is printed.

[8]: b

[8]: 'what a course!'

Python is case sensitive, in variable names distinguishes between cases, i.e. a and A are different
symbols:

[9]: a = 5
A = (1 + 3**3) / 2
a, A

[9]: (5, 14.0)

1.3 Super Calculator


Just like in pocket calculators you can use mathematical functions. The difference is that you need
to import the function before using it:

[10]: from math import sqrt

(1 - sqrt(3)) / (2 * 9 ** (1 / 4) - 2)

[10]: -0.5

Some considerations regarding the Python code so far:

• Some math functions need to be imported before being used.


• Lower case and upper case correspond to different symbols.
• The exponentiation operator is represented by **.

Numerical Methods for Economics Master in Economics


2 Working with multiple values at once 9

• The last value was returned in the output.

In Jupyter, in order to allow us to more easily see the results of calculations, if the last expression
is not assigned to a variable then it will always be shown.
That is why the last result is printed even if we did not called the print function that is the
usual way to do it in Python. This is specific to Jupyter and it is related with the interactive use
philosophy of this tool.
Notice, though, that the same remarks regarding the precision of the results versus the presenta-
tion of the results applies here without any exception. This will be a meme of the course so please
remember this.

2 Working with multiple values at once


An important task for computation is data handling. In order to simplify this process Python pro-
vides different data types.
An example of such data structure is a list. In this example we will show how to create, access
each element in the list and finally how to modify its content:

[11]: letters = ["a", "b", "c", "d", "e"]

numbers = [1, 2, 3, 4, 5]

The first element in a list is at position 0 and is indexed using square brackets []:

[12]: numbers[0]

[12]: 1

This is a design choice. Sometimes it is useful and others it is not (there are cases where it helps
that the index start at zero).
In case you think that this possible confusion is only specific to Python and the last in position
-1:

[13]: numbers[-1]

[13]: 5

We can get a set of elements by position by passing a range

[14]: letters[2:4]

[14]: ['c', 'd']

Note that the ranges in Python include the lower boundary but do not include the upper boundary.
So in the case above we get the elements that are in position 2 and 3, but not 4.
We can alter the contents of a list by specifying the new value for a particular position:

Numerical Methods for Economics Master in Economics


3 Saving the work 10

[15]: letters[0] = "A"


letters

[15]: ['A', 'b', 'c', 'd', 'e']

The same can be done for a given range of values:

[16]: numbers[2:4] = [-3, -4]


numbers

[16]: [1, 2, -3, -4, 5]

3 Saving the work


The notebooks are automatically saved with extension .ipynb as a notebook. The notebooks are
automatically saved at periodic intervals. If necessary, or desired, we can save the work manually.
Press the floppy disc above or go to the menu File->Save notebook.
The notebooks will retain both the input and output results and can be used later.
Furthermore, other possible output formats are available like .html, .py and .pdf among others;
to do so go to File->Save and Export Notebook As..., and take your choice. This automati-
cally gives you a way to store your work in a way that can be easily be consulted later.

4 Conclusion
In this notebook we have explored both Python and Markdown.
The purpose of this exercise was two-fold: first to explore some simple calculations in Python
and also to see how text can be spread to explain what is being done.
The purpose of these notebooks is allow students to be able to test the code and to make changes
to see what changes. Remember that the best way to learn any language, human or not, is to
practice it. Remember also that you have the original notebooks available so do not be afraid to
change them.
In the next notebooks, of this module, we will explore both the Python language and Markdown
in more detail.

Numerical Methods for Economics Master in Economics


11

Notebook 3.2 - Introduction to


Markdown
Contents
1 Introduction 12
1.1 Lecture notes example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

2 Heading - level 1 12
2.1 Heading - level 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.1.1 Heading - level 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

3 Hypertext 13
3.1 Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.2 Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

4 Logical formatting 14
4.1 Inline text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
4.2 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
4.2.1 Itemized . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
4.2.2 Numbered . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
4.2.3 Nested lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

5 Special paragraph types 15


5.1 Blockquote . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.2 Code inside Markdown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

6 Special formats 16
6.1 Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
6.2 Horizontal rules (separators) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
6.3 Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

7 Conclusion 16

Numerical Methods for Economics Master in Economics


1 Introduction 12

1 Introduction
The purpose of this notebook is to give some examples regarding the use of Markdown in a note-
book.
The idea behind Markdown is that simply by the way as we write we are inferring some format.
Jupyter supports then Markdown by converting the Markdown from simple text to the rendered
view where the format is then seen as it is intended.
Markdown cells, like this one, even when used in the editable form show some hints regarding
the different elements. Usually that happens by the use of colors or other elements to show that the
content is using a special format.

1.1 Lecture notes example


This is the example from the lecture notes.
This is a list of items:

• 1
• 2
• 3

To see how the examples look in raw text double click with the mouse over each cell. To render
the markup cell you can type Shift+Enter as you would to execute a code cell.
In order to change a cell into the editable form double click over it and it can be changed again.

2 Heading - level 1
One way to structure documents is to use heading levels, that work similarly to a hierarchy:

• Chapter;
• Section;
• Subsection;
• Subsubsection;

In order to do that we distinguish each level by the number of # (hash mark) that we use.
For the first level we use a single one, in the next level we use two, and so on.

2.1 Heading - level 2


This structure allow us to give an understandable structure to our document.
In Jupyter Lab in the left side there is “Table of Contents” widget that allows us to easily
navigate the document.
At the same time for some of the exported formats they are numbered allowing us to use format
similar to books or other documents.

Numerical Methods for Economics Master in Economics


3 Hypertext 13

Figure 1: Porto Economics and Management School

2.1.1 Heading - level 3


This organization of the notebook gives the reader and order of importance and the relation between
the different content of the notebook.

3 Hypertext
Hypertext is the basis of the Internet content. We can link the text to some resource, either local
or on the internet.
In order to do that we use URL (Universal Resource Locator) just like those seen in the browser’s
location.

3.1 Links
The way to use links in Markdown is to use the format [description](url), where between
square brackets we get the description of the content that we are linking and between parenthesis
goes the content’s url.
Example: > In the Quantitative Economics website you can find lots of resources. This site
project intends to explore Quantitative Economics and Finance with the help of Python.

3.2 Images
Images are very similar to hypertext links. The only difference is that images are prefixed by an
exclamation mark (!). So the format is ![image caption](url), now the text is the image caption,
that you usually get when you hoover the mouse over the image and the url can either be local or a
full URL location.
Example: This course is held at University of Porto.
Another option would have been to change the above URL with the image file location: [Link]
agens/LogotipoSI.

Numerical Methods for Economics Master in Economics


4 Logical formatting 14

4 Logical formatting
Markdown is a simple way to format text that looks great on any device. It does not do anything
fancy like change the font size, color, or type - just the essentials, using keyboard symbols you
already know.

4.1 Inline text


Examples:

• To emphasize text, italic, we can use either Italic or Italic.


• For a different kind of emphasis we can use Bold or Bold.

4.2 Lists
4.2.1 Itemized
• List
• List
• List

or

• List
• List
• List

4.2.2 Numbered
1. One
2. Two
3. Three

or

1) One
2) Two
3) Three

4.2.3 Nested lists


We can have the different lists nested inside each other. The way to do it is to indent to code inside
each list. Notice also that the way as the lists are rendered is done according to the level where the
list is:

1. One

Numerical Methods for Economics Master in Economics


5 Special paragraph types 15

• 1.1
• 1.2
2. Two
• 2.1
1. 2.1.1
2. 2.1.2
• 2.2
• 2.3

As you can see in this example indentation implies meaning, in this case the level of indentation.

5 Special paragraph types


5.1 Blockquote
Appending a single > will mark it as block quote (similar to email text format):

To quote a block, as an example to quote some authors we can the block quote. Lorem
ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.

5.2 Code inside Markdown


We can create a document where some code is is mixed inside the code. This code is different from
the code cells, since the code in the code cells can be run but the code that is in the text it is just
documentation.
There are two possible ways, either inside some paragraph or whole paragraphs of code.
We can add inline code, inside Markdown, placing the code inside backticks.
Example: > Run import this to see the Zen of Python.
For larger pieces of code we use a block version:

# code block
print ('3 backticks or')
print ('indent 4 spaces')

Numerical Methods for Economics Master in Economics


6 Special formats 16

6 Special formats
6.1 Math
We can also typeset mathematical formulas, e.g.

𝐸 = 𝑚𝑐2 .

The syntax is similar to LaTeX.

6.2 Horizontal rules (separators)


We can also use an horizontal rule to separate some text.

or

6.3 Tables
It is possible to typeset tables in text. Notice that we determine how the columns should be aligned
in the second row below:

head col1 col2


1 2 3

7 Conclusion
The advantage of using Markdown in notebooks is that it allows us to mix text, images and code in
a single document. This is also known as literate programming.
The format of the notebooks allows to mix the documentation with the code and its output:

[1]: import this

The Zen of Python, by Tim Peters

Beautiful is better than ugly.


Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.

Numerical Methods for Economics Master in Economics


7 Conclusion 17

Special cases aren't special enough to break the rules.


Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

This notebook is just an example. To know more you can find further examples in:

• these lecture notes;


just open the notebooks, double click on each text cell, and you will see what is the raw
format. Pressing Ctr+Enter (or Cmd+Enter if you are on a Mac) or using any other option
will change that to the render format (nice looking format).

• the Markdown tutorial.

Numerical Methods for Economics Master in Economics


18

Notebook 3.3 - Scientific Python


Quickstart
Contents
1 Scientific Python Quickstart 19
1.1 Basic NumPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.1.1 Creating arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.1.2 Array indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.1.3 Array methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.1.4 Operations on arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.1.5 Comparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
1.2 Matplotlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
1.3 SciPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
1.3.1 Statistics and distributions . . . . . . . . . . . . . . . . . . . . . . . . . 27
1.3.2 Roots and fixed points . . . . . . . . . . . . . . . . . . . . . . . . . . 31
1.3.3 Numerical optimization and integration . . . . . . . . . . . . . . . . . . 33
1.3.4 Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
1.3.5 More information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
1.4 Pandas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
1.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
1.6 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 19

1 Scientific Python Quickstart


John Stachurski

ANU This is a fast-paced, hands-on introduction to scientific computing with Python, contained in
a Jupyter notebook. The main focus will be on introducing Python’s four most important scientific
libraries: NumPy, Scipy, Pandas and Matplotlib.
If you don’t know how to use this notebook you need to first work through this page.
A slower, more detailed and more systematic treatment of Python for scientific applications can
be found at [Link]. But this notebook is a good place to start for those who like to learn
by doing.
Here’s some information on the version of Python that I’m using:

[1]: import sys

print([Link])

3.14.0rc2 (main, Aug 14 2025, 00:00:00) [GCC 15.2.1 20250808 (Red Hat 15.2.1-1)]

1.1 Basic NumPy


Perhaps the single most important scientific library for Python is NumPy. NumPy provides foun-
dational data structures and routines on which many other libraries rely.

[2]: import numpy as np # Import library and give it alias np

print(np.__version__) # The version I'm using

2.3.3

NumPy defines a basic data type called an array (actually a [Link])

[3]: a = [Link](3) # Create an array of zeros


a # Print a

[3]: array([0., 0., 0.])

[4]: type(a)

[4]: [Link]

Note that array data must be homogeneous


The most important data types are:

• float64: 64 bit floating point number


• float32: 32 bit floating point number
• int64: 64 bit integer

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 20

• int32: 32 bit integer


• bool: 8 bit True or False

There are also dtypes to represent complex numbers, unsigned integers, etc
On most machines, the default dtype for arrays is float64

[5]: a = [Link](3)
type(a[1])

[5]: numpy.float64

When we create an array such as

[6]: z = [Link](10)

z is a “flat” array with no dimension— neither row nor column vector:

[7]: [Link]

[7]: (10,)

Here the shape tuple has only one element, which is the length of the array (tuples with one
element end with a comma)
To give it dimension, we can change the shape attribute
For example, let’s make it a column vector

[8]: [Link] = (10, 1)

[9]: z

[9]: array([[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.]])

[10]: z = [Link](4)
[Link] = (2, 2)
z

[10]: array([[0., 0.],


[0., 0.]])

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 21

1.1.1 Creating arrays


Creating empty arrays — initializing memory:

[11]: z = [Link](3)
z

[11]: array([1.14421405e-313, 0.00000000e+000, 3.60788770e-317])

These are just garbage numbers — whatever was in those memory slots
Here’s how to make a regular gird sequence

[12]: z = [Link](2, 4, 5) # From 2 to 4, with 5 elements


z

[12]: array([2. , 2.5, 3. , 3.5, 4. ])

Creating an array of ones

[13]: z = [Link](3)
z

[13]: array([1., 1., 1.])

[14]: z = [Link](2)
z

[14]: array([[1., 0.],


[0., 1.]])

Arrays can be made from Python lists or tuples

[15]: z = [Link]([10, 20])


z

[15]: array([10, 20])

[16]: z = [Link]((10, 20), dtype=float)


z

[16]: array([10., 20.])

[17]: z = [Link]([[1, 2], [3, 4]]) # 2D array from a list of lists


z

[17]: array([[1, 2],


[3, 4]])

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 22

1.1.2 Array indexing

[18]: z = [Link](1, 2, 5)
z

[18]: array([1. , 1.25, 1.5 , 1.75, 2. ])

[19]: z[0] # First element --- Python sequences are zero based, like C, Java, etc.

[19]: np.float64(1.0)

[20]: z[-1] # Special syntax for last element

[20]: np.float64(2.0)

[21]: z[0:2] # Meaning: Two elements, starting from element 0

[21]: array([1. , 1.25])

[22]: z = [Link]([[1, 2], [3, 4]])


z

[22]: array([[1, 2],


[3, 4]])

[23]: z[0, 0]

[23]: np.int64(1)

[24]: z[0, :] # First row

[24]: array([1, 2])

[25]: z[:, 0] # First column

[25]: array([1, 3])

[26]: z = [Link](2, 4, 5)
z

[26]: array([2. , 2.5, 3. , 3.5, 4. ])

[27]: d = [Link]([0, 1, 1, 0, 0], dtype=bool)


d

[27]: array([False, True, True, False, False])

[28]: z[d]

[28]: array([2.5, 3. ])

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 23

1.1.3 Array methods

[29]: A = [Link]((4, 3, 2, 1))


A

[29]: array([4, 3, 2, 1])

[30]: [Link]()

[31]: A

[31]: array([1, 2, 3, 4])

[32]: [Link]()

[32]: np.float64(2.5)

[33]: [Link]()

[33]: np.int64(10)

[34]: [Link]()

[34]: np.int64(4)

[35]: [Link]()

[35]: array([ 1, 3, 6, 10])

[36]: [Link]()

[36]: np.float64(1.25)

[37]: [Link] = (2, 2)


A

[37]: array([[1, 2],


[3, 4]])

[38]: A.T # Transpose, equivalent to [Link]()

[38]: array([[1, 3],


[2, 4]])

1.1.4 Operations on arrays


Standard arithmetic operations on arrays act elementwise

[39]: a = [Link]([1, 2, 3, 4])


b = [Link]([5, 6, 7, 8])

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 24

[40]: a + b

[40]: array([ 6, 8, 10, 12])

[41]: a - b

[41]: array([-4, -4, -4, -4])

[42]: a + 10

[42]: array([11, 12, 13, 14])

[43]: [Link] = 2, 2
[Link] = 2, 2

[44]: a

[44]: array([[1, 2],


[3, 4]])

[45]: b

[45]: array([[5, 6],


[7, 8]])

[46]: a * b # Pointwise multiplication!!

[46]: array([[ 5, 12],


[21, 32]])

[47]: [Link](a, b) # Matrix multiplication

[47]: array([[19, 22],


[43, 50]])

For Python ≥ 3.5 and NumPy ≥ 1.1 the @ operator also works.

[48]: a @ b

[48]: array([[19, 22],


[43, 50]])

I’ll continue to use [Link] below for the benefit of those who are using older versions. But in
my opinion the @ operator is much nicer.

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 25

1.1.5 Comparisons

[49]: z = [Link]([2, 3])


y = [Link]([2, 3])
z == y

[49]: array([ True, True])

[50]: y[0] = 3
z == y

[50]: array([False, True])

[51]: z = [Link](0, 10, 5)


z

[51]: array([ 0. , 2.5, 5. , 7.5, 10. ])

[52]: z > 3

[52]: array([False, False, True, True, True])

[53]: z[z > 3] # Conditional extraction

[53]: array([ 5. , 7.5, 10. ])

1.2 Matplotlib
Matplotlib is an outstanding plotting and visualization library for Python that interacts nicely with
NumPy. Here are a few quick examples. We’ll see more below when we discuss the SciPy library.

[54]: import [Link] as plt # Import main functionality

Display figures in this browser window rather than having them open up separately:

[55]: %matplotlib inline

Create something to plot

[56]: x = [Link](-2, 2, 100)


y = x**2

[57]: fig, ax = [Link]() # Create axes and figure window


[Link](x, y, "b-")

[57]: [<[Link].Line2D at 0x7f8cc2a812b0>]

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 26

Here’s a slightly more complex plot

[58]: y3 = x**3
fig, ax = [Link]() # Create axes and figure window
[Link](x, y, "b-", lw=2, alpha=0.8, label="$x^2$")
[Link](x, y3, "g-", lw=2, alpha=0.8, label="$x^3$")
[Link](loc="lower right")

[58]: <[Link] at 0x7f8cc2aeb770>

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 27

1.3 SciPy
Let’s just cover some simple examples — references for further reading are below

1.3.1 Statistics and distributions


Let’s use [Link] to generate some data from the Beta distribution

[59]: from [Link] import beta

q = beta(5, 5) # Beta(a, b), with a = b = 5


obs = [Link](2000) # 2000 observations

Now let’s histogram it and compare it to the original density

[60]: fig, ax = [Link]()


[Link](obs, bins=40, density=True)
grid = [Link](0.01, 0.99, 100)
[Link](grid, [Link](grid), "k-", linewidth=2)

[60]: [<[Link].Line2D at 0x7f8cb6c68ec0>]

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 28

Other methods

[61]: type(q)

[61]: [Link]._distn_infrastructure.rv_continuous_frozen

[62]: dir(q) # Let's see all its methods

[62]: ['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__firstlineno__',
'__format__',
'__ge__',
'__getattribute__',
'__getstate__',
'__gt__',
'__hash__',

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 29

'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__static_attributes__',
'__str__',
'__subclasshook__',
'__weakref__',
'a',
'args',
'b',
'cdf',
'dist',
'entropy',
'expect',
'interval',
'isf',
'kwds',
'logcdf',
'logpdf',
'logsf',
'mean',
'median',
'moment',
'pdf',
'ppf',
'random_state',
'rvs',
'sf',
'stats',
'std',
'support',
'var']

[63]: [Link](0.5)

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 30

[63]: np.float64(0.5)

[64]: [Link](0.5)

[64]: np.float64(2.4609374999999996)

[65]: [Link]()

[65]: np.float64(0.5)

Basic linear regression:

[66]: from [Link] import linregress

n = 100
alpha, beta, sigma = 1, 2, 1.5
x = [Link](n) # n standard normals
y = alpha + beta * x + sigma * [Link](n)
beta_hat, alpha_hat, r_value, p_value, std_err = linregress(x, y)
print("gradient = {}".format(beta_hat))
print("intercept = {}".format(alpha_hat))

gradient = 1.8545073907619496
intercept = 0.9610926535807708

Let’s plot this with data and line of best fit

[67]: fig, ax = [Link](figsize=(8, 5))


[Link](x, y, "bo", alpha=0.6, label="observations")
xgrid = [Link](-3, 3, 2)
[Link](xgrid, alpha_hat + beta_hat * xgrid, "k-", lw=2, alpha=0.8, label="best fit")
[Link]()
[Link](loc="upper left")

[67]: <[Link] at 0x7f8cb6d152b0>

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 31

1.3.2 Roots and fixed points


Let’s choose an arbitrary function to work with

[68]: fig, ax = [Link]()

def f(x):
return [Link](4 * (x - 0.25)) + x + x**20 - 1

x = [Link](0, 1, 100)
[Link](x, f(x))
[Link](x, 0 * x)

[68]: [<[Link].Line2D at 0x7f8cb6b9a900>]

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 32

[69]: from [Link] import bisect # Bisection algorithm --- slow but robust

bisect(f, 0, 1)

[69]: 0.4082935042806639

[70]: from [Link] import newton # Newton's method --- fast but less robust

newton(f, 0.2) # Start the search at initial condition x = 0.2

[70]: np.float64(0.40829350427935673)

[71]: newton(f, 0.7) # Start the search at x = 0.7 instead

[71]: np.float64(0.7001700000000279)

Here we see that the algorithm gets it wrong — newton is fast but not robust
Let’s try a hybrid method

[72]: from [Link] import brentq

brentq(f, 0, 1) # Hybrid method

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 33

[72]: 0.40829350427936706

[73]: timeit bisect(f, 0, 1)

107 μs ± 4.22 μs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

[74]: timeit newton(f, 0.2)

116 μs ± 3.76 μs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

[75]: timeit brentq(f, 0, 1)

26.7 μs ± 147 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

Note that the hybrid method is robust but still quite fast…

1.3.3 Numerical optimization and integration

[76]: from [Link] import fminbound

fminbound(lambda x: x**2, -1, 2) # Search in [-1, 2]

[76]: np.float64(0.0)

[77]: from [Link] import quad

integral, error = quad(lambda x: x**2, 0, 1)


integral

[77]: 0.33333333333333337

1.3.4 Linear Algebra


Let’s look at some of the most common routines from linear and matrix algebra

[78]: import [Link] as la

We’ll experiment with matrices

2 −1 1
𝐴=[ ] and 𝑏=[ ]
3 0 1

[79]: A = [[2, -1], [3, 0]]


A = [Link](A) # Convert from list to NumPy array
b = [Link]((2, 1)) # Shape is 2 x 1

[80]: A

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 34

[80]: array([[ 2, -1],


[ 3, 0]])

[81]: b

[81]: array([[1.],
[1.]])

[82]: x = [Link](A, b) # Solve for x in Ax = b


print(x)

[[ 0.33333333]
[-0.33333333]]

Let’s check that 𝐴𝑥 = 𝑏

[83]: [Link](A, x)

[83]: array([[1.],
[1.]])

We can also invert directly

[84]: [Link](A)

[84]: array([[ 0. , 0.33333333],


[-1. , 0.66666667]])

[85]: [Link](A, [Link](A)) # Should be the identity

[85]: array([[1., 0.],


[0., 1.]])

Let’s compute the eigenvalues and eigenvectors

[86]: eigvals, eigvecs = [Link](A)

[87]: print("eigenvalues = {}".format(eigvals))

eigenvalues = [1.+1.41421356j 1.-1.41421356j]

[88]: print("first eigenvector = {}".format(eigvecs[:, 0]))

first eigenvector = [0.28867513+0.40824829j 0.8660254 +0.j ]

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 35

1.3.5 More information


• linear algebra: [Link]
• numerical integration: [Link]
• interpolation: [Link]
• optimization: [Link]
• distributions and random number generation: [Link]
• signal processing: [Link]

1.4 Pandas
Pandas is a very popular library for working with data sets. In pandas, data is held in a dataframe,
which is kind of like a spread sheet

[89]: import pandas as pd

Let’s start by writing a test data set to the present working directory, so we can read it back in
as a dataframe using pandas. We use an IPython magic to write the data from a cell to a file:

[90]: %%file ../data/test_data.csv


"country","country isocode","year","POP","XRAT","tcgdp","cc","cg"
"Argentina","ARG","2000","37335.653","0.9995","295072.21869","75.716805379","5.5788042896"
"Australia","AUS","2000","19053.186","1.72483","541804.6521","67.759025993","6.7200975332"
"India","IND","2000","1006300.297","44.9416","1728144.3748","64.575551328","14.072205773"
"Israel","ISR","2000","6114.57","4.07733","129253.89423","64.436450847","10.266688415"
"Malawi","MWI","2000","11801.505","59.543808333","5026.2217836","74.707624181","11.658954494"
"South Africa","ZAF","2000","45064.098","6.93983","227242.36949","72.718710427","5.7265463933"
"United States","USA","2000","282171.957","1","9898700","72.347054303","6.0324539789"
"Uruguay","URY","2000","3219.793","12.099591667","25255.961693","78.978740282","5.108067988"

Overwriting ../data/test_data.csv

[91]: %ls ../data/*.csv # Check it's there

../data/test_data.csv

[92]: df = pd.read_csv("../data/test_data.csv")

[93]: df

[93]: country country isocode year POP XRAT tcgdp \


0 Argentina ARG 2000 37335.653 0.999500 2.950722e+05
1 Australia AUS 2000 19053.186 1.724830 5.418047e+05
2 India IND 2000 1006300.297 44.941600 1.728144e+06
3 Israel ISR 2000 6114.570 4.077330 1.292539e+05
4 Malawi MWI 2000 11801.505 59.543808 5.026222e+03
5 South Africa ZAF 2000 45064.098 6.939830 2.272424e+05

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 36

6 United States USA 2000 282171.957 1.000000 9.898700e+06


7 Uruguay URY 2000 3219.793 12.099592 2.525596e+04

cc cg
0 75.716805 5.578804
1 67.759026 6.720098
2 64.575551 14.072206
3 64.436451 10.266688
4 74.707624 11.658954
5 72.718710 5.726546
6 72.347054 6.032454
7 78.978740 5.108068

Let’s try that again but this time using the country as the index column

[94]: df = pd.read_csv("../data/test_data.csv", index_col="country")

[95]: df

[95]: country isocode year POP XRAT tcgdp \


country
Argentina ARG 2000 37335.653 0.999500 2.950722e+05
Australia AUS 2000 19053.186 1.724830 5.418047e+05
India IND 2000 1006300.297 44.941600 1.728144e+06
Israel ISR 2000 6114.570 4.077330 1.292539e+05
Malawi MWI 2000 11801.505 59.543808 5.026222e+03
South Africa ZAF 2000 45064.098 6.939830 2.272424e+05
United States USA 2000 282171.957 1.000000 9.898700e+06
Uruguay URY 2000 3219.793 12.099592 2.525596e+04

cc cg
country
Argentina 75.716805 5.578804
Australia 67.759026 6.720098
India 64.575551 14.072206
Israel 64.436451 10.266688
Malawi 74.707624 11.658954
South Africa 72.718710 5.726546
United States 72.347054 6.032454
Uruguay 78.978740 5.108068

Let’s drop the year since it’s not very informative

[96]: df = [Link](["year"], axis=1)


df

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 37

[96]: country isocode POP XRAT tcgdp \


country
Argentina ARG 37335.653 0.999500 2.950722e+05
Australia AUS 19053.186 1.724830 5.418047e+05
India IND 1006300.297 44.941600 1.728144e+06
Israel ISR 6114.570 4.077330 1.292539e+05
Malawi MWI 11801.505 59.543808 5.026222e+03
South Africa ZAF 45064.098 6.939830 2.272424e+05
United States USA 282171.957 1.000000 9.898700e+06
Uruguay URY 3219.793 12.099592 2.525596e+04

cc cg
country
Argentina 75.716805 5.578804
Australia 67.759026 6.720098
India 64.575551 14.072206
Israel 64.436451 10.266688
Malawi 74.707624 11.658954
South Africa 72.718710 5.726546
United States 72.347054 6.032454
Uruguay 78.978740 5.108068

Let’s add a column for GDP per capita

[97]: df["GDP percap"] = df["tcgdp"] / df["POP"]

[98]: df

[98]: country isocode POP XRAT tcgdp \


country
Argentina ARG 37335.653 0.999500 2.950722e+05
Australia AUS 19053.186 1.724830 5.418047e+05
India IND 1006300.297 44.941600 1.728144e+06
Israel ISR 6114.570 4.077330 1.292539e+05
Malawi MWI 11801.505 59.543808 5.026222e+03
South Africa ZAF 45064.098 6.939830 2.272424e+05
United States USA 282171.957 1.000000 9.898700e+06
Uruguay URY 3219.793 12.099592 2.525596e+04

cc cg GDP percap
country
Argentina 75.716805 5.578804 7.903229
Australia 67.759026 6.720098 28.436433
India 64.575551 14.072206 1.717325
Israel 64.436451 10.266688 21.138673

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 38

Malawi 74.707624 11.658954 0.425897


South Africa 72.718710 5.726546 5.042648
United States 72.347054 6.032454 35.080382
Uruguay 78.978740 5.108068 7.843971

Let’s sort the whole data frame by GDP per capita

[99]: df = df.sort_values(by="GDP percap")

[100]: df

[100]: country isocode POP XRAT tcgdp \


country
Malawi MWI 11801.505 59.543808 5.026222e+03
India IND 1006300.297 44.941600 1.728144e+06
South Africa ZAF 45064.098 6.939830 2.272424e+05
Uruguay URY 3219.793 12.099592 2.525596e+04
Argentina ARG 37335.653 0.999500 2.950722e+05
Israel ISR 6114.570 4.077330 1.292539e+05
Australia AUS 19053.186 1.724830 5.418047e+05
United States USA 282171.957 1.000000 9.898700e+06

cc cg GDP percap
country
Malawi 74.707624 11.658954 0.425897
India 64.575551 14.072206 1.717325
South Africa 72.718710 5.726546 5.042648
Uruguay 78.978740 5.108068 7.843971
Argentina 75.716805 5.578804 7.903229
Israel 64.436451 10.266688 21.138673
Australia 67.759026 6.720098 28.436433
United States 72.347054 6.032454 35.080382

Now we’ll plot per capital GDP using the dataframe’s plot method

[101]: df["GDP percap"].plot(kind="bar")

[101]: <Axes: xlabel='country'>

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 39

1.5 Exercises
Here are two exercises. Feel free to consult documentation such as can be found here. The solutions
are below. The cell with “solution below” is mean to push them below your line of sight and save
you from temptation.

Exercise 1 Generate 10000 data points from the exponential distribution with density

𝑓(𝑥; 𝛼) = 𝛼 exp(−𝛼𝑥) (𝑥 > 0, 𝛼 > 0)


using [Link] and taking 𝛼 = 0.5. Then, after looking up the maximum likelihood esti-
mator of 𝛼, compute the estimate given your data and check that it is in fact close to 𝛼.

[102]: # Put your solution here

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 40

Exercise 2 Using the same data set, implement maximum likelihood again, but this time pre-
tending that you don’t know the analytical expression for the maximum likelihood estimator. Set
up the log likelihood function and maximize it numerically using a routine from [Link].

[103]: # Put your solution here

1.6 Solutions
[104]: # Print some nonsense to partially hide solutions
filler_text = "solution below\n" * 25
print(filler_text)

solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below

Solution to Exercise 1 After checking the docs for the exponential distribution we proceed as
follows

[105]: from [Link] import expon

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 41

alpha = 0.5
n = 10000
ep = expon(scale=1.0 / alpha) # scale controls the exponential parameter
x = [Link](n)

Let’s check we’ve got the right distribution here

[106]: fig, ax = [Link](figsize=(8, 5))


xmin, xmax = 0.001, 10.0
ax.set_xlim(xmin, xmax)
[Link](x, density=True, bins=40, alpha=0.3)
grid = [Link](xmin, xmax, 200)
[Link](grid, [Link](grid), "g-", lw=2, label="true density")
[Link]()

[106]: <[Link] at 0x7f8ca767dfd0>

It’s well-known that the MLE of 𝛼 is 1/𝑥̄ where 𝑥̄ is the mean of the sample. Let’s check that
it is indeed close to 𝛼.

[107]: alpha_mle = 1.0 / [Link]()


print("max likelihood estimate of alpha is {}".format(alpha_mle))

max likelihood estimate of alpha is 0.5029584857659946

Numerical Methods for Economics Master in Economics


1 Scientific Python Quickstart 42

[108]: s = [Link]()

def neg_loglike(a):
"Minus the log likelihood function for exponential"
return -n * [Link](a) + a * s

Minimize over a reasonable parameter space

[109]: from [Link] import fminbound

fminbound(neg_loglike, 0.01, 10.0)

[109]: np.float64(0.5029574781104512)

This is very close to the analytical value of the max likelihood estimator we got in exercise 1

Numerical Methods for Economics Master in Economics


43

Notebook 4.1 - Linear supply and


demand model
Contents
1 Supply and demand model 44

2 Basic version 44
2.1 Solving by equations by hand . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
2.2 Matrix formulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

3 Model with taxes 47

Numerical Methods for Economics Master in Economics


1 Supply and demand model 44

1 Supply and demand model


In this section we solve the supply and demand model (presented in the lecture notes).

1. Consider the following supply and demand curves: 𝑝 = 𝑐 + 𝑑 × 𝑞 and 𝑝 = 𝑎 − 𝑏 × 𝑞 for


𝑎 = 10, 𝑏 = 0.7, 𝑐 = 2 and 𝑑 = 0.5.
1. Draw the equations;
2. Compute the equilibrium point;
3. Represent it graphically.
2. Consider the existence of taxes 𝑡 at the model: 𝑝 + 𝑡 = 𝑎 − 𝑏 × 𝑞 and 𝑝 = 𝑐 + 𝑑 × 𝑞:
1. What is the new equilibrium quantity (take t=1)?
2. What is the equilibrium price paid by consumers and the price perceived by producers?
3. What is the tax collected by the government?

2 Basic version
2.1 Solving by equations by hand
[1]: import numpy as np
import [Link] as plt

# demand/supply model:
# p = a - b q
# p = c + d q
a = 10
b = 0.7
c = 2
d = 0.5

# Evaluate price of supply and demand for several productions


q = [Link](0, 15) # q = [Link]([0, 1, 2,..., 14])
pd = a - b * q
ps = c + d * q

[2]: # display table


[Link]((q, pd, ps), axis=1)

[2]: array([[ 0. , 10. , 2. ],


[ 1. , 9.3, 2.5],
[ 2. , 8.6, 3. ],
[ 3. , 7.9, 3.5],
[ 4. , 7.2, 4. ],
[ 5. , 6.5, 4.5],

Numerical Methods for Economics Master in Economics


2 Basic version 45

[ 6. , 5.8, 5. ],
[ 7. , 5.1, 5.5],
[ 8. , 4.4, 6. ],
[ 9. , 3.7, 6.5],
[10. , 3. , 7. ],
[11. , 2.3, 7.5],
[12. , 1.6, 8. ],
[13. , 0.9, 8.5],
[14. , 0.2, 9. ]])

[3]: # graphical representation

# plot supply and demand curves


[Link](1)
[Link](q, pd, "r")
[Link](q, ps, "b")
[Link]([0, 15, 0, 10])
[Link]("q")
[Link]("p")

# evaluate equilibrium: qd = qs
qeq = (a - c) / (b + d)
peq = (a * d + b * c) / (b + d)
print(f"Equilibrium price and quantity: {peq:.3}, {qeq:.3}")

# plot equilibrium point in the plot


[Link](qeq, peq, "o")
[Link]("Supply and demand model")

Equilibrium price and quantity: 5.33, 6.67

[3]: Text(0.5, 1.0, 'Supply and demand model')

Numerical Methods for Economics Master in Economics


2 Basic version 46

2.2 Matrix formulation


The previous example was solved in a calculator way, i.e., we expanded the expressions by hand in
order to get the right results. That is nice but tedious. If the number of unknowns is larger than 3
then this approach becomes unpractical.
In this case the problem above is the same as
𝑝 + 𝑏.𝑞 = 𝑎
{
𝑝 − 𝑑.𝑞 = 𝑐
This corresponds to a linear system with coefficients
1 𝑏
𝐴=[ ]
1 −𝑑
and independent terms
𝑎
𝑓 =[ ]
𝑐
and so the solution is the solution of the linear system
𝐴𝑥 = 𝑓

Numerical Methods for Economics Master in Economics


3 Model with taxes 47

[4]: A = [Link]([[1, b], [1, -d]])


f = [Link]([a, c])
[Link](A, f)

[4]: array([5.33333333, 6.66666667])

3 Model with taxes


Now we solve the same example adding taxes.

[5]: # demand/supply with government (taxes):


# p + t = a - b * q and p = c + d * q
a = 10
b = 0.7
c = 2
d = 0.5
t = 1

# equilibrium quantity
qeq = (a - (c + t)) / (b + d)

# equilibrium price
# (price payed by consumers and price perceived by producers)
pc = (a * d + b * (c + t)) / (b + d)
pp = ((a - t) * d + b * c) / (b + d)

print(f"consumer price {pc:.3}")


print(f"producer price {pp:.3}")
print(f"tax (quantity) {qeq:.3}")
print(f"tax collected {t * qeq:.3}")

consumer price 5.92


producer price 4.92
tax (quantity) 5.83
tax collected 5.83

Numerical Methods for Economics Master in Economics


48

Notebook 4.2 - Consumer and


producer surplus
Contents
1 Definition 49

2 Application 49

Numerical Methods for Economics Master in Economics


1 Definition 49

1 Definition
Consumer surplus, or consumers’ surplus, is the monetary gain obtained by consumers because
they are able to purchase a product for a price that is less than the highest price that they would be
willing to pay.
Producer surplus, or producers’ surplus, is the amount that producers benefit by selling at a
market price that is higher than the least that they would be willing to sell for.
Tasks:
𝑞
1. Compute the consumer surplus ∫ 𝑒 (𝐷(𝑞) − 𝑝𝑒 )𝑑𝑞.
0
𝑞
2. Compute the producer surplus ∫ 𝑒 (𝑝𝑒 − 𝑆(𝑞))𝑑𝑞.
0

2 Application
We will the supply and demand model previously explored in the previous notebook.

[1]: import numpy as np


import [Link] as plt
from [Link] import quad as integral
from [Link] import Polygon

# demand/supply model:
# p = a - b q
# p = c + d q
a = 10
b = 0.7
c = 2
d = 0.5

# evaluate equilibrium: qd = qs
qeq = (a - c) / (b + d)
peq = (a * d + b * c) / (b + d)

# Evaluate price of supply and demand


q = [Link](0, 15)
pd = a - b * q
ps = c + d * q

# evaluate surplus using functions


# we need to define functions since integrals acts on functions
CS = integral(lambda p: (a - p) / b - peq, 0, qeq)[0]
PS = integral(lambda p: peq - (p - c) / d, 0, qeq)[0]
print(f"consumer surplus: {CS:.3}")

Numerical Methods for Economics Master in Economics


2 Application 50

print(f"producer surplus: {PS:.3}")

# graphical representation
fig, ax = [Link]()
[Link](q, pd, "r")
[Link](q, ps, "b")
[Link](qeq, peq, "o")
[Link]([0, 10, 0, 10])

ax.add_patch(Polygon([(0, peq), (0, a), (qeq, peq)], facecolor="green"))


ax.add_patch(Polygon([(0, peq), (0, c), (qeq, peq)], facecolor="yellow"))
[Link](1, 7, "consumer surplus")
[Link](1, 4, "producer surplus")

[Link]("q")
[Link]("p")
[Link]("Consumer and producer surplus");

consumer surplus: 27.9


producer surplus: 17.8

Numerical Methods for Economics Master in Economics


2 Application 51

Numerical Methods for Economics Master in Economics


52

Notebook 4.3 - Lorenz curve and Gini


coefficient
Contents
1 Definition 53

2 Example 53

3 (Re)solution 53
3.1 Import packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
3.2 Input data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.3 Prepare the data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.4 Evaluate the Lorenz curve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.5 Display Lorenz curve values . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.6 Plot Lorenz curve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
3.7 Evaluate the Gini coefficient . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

Numerical Methods for Economics Master in Economics


1 Definition 53

1 Definition
The Lorenz curve and Gini coefficient are used to study the inequality in the distribution of re-
sources, usually wealth, in a given population.
For more details on this consult the Wikipedia entry on the Gini Coefficient.

2 Example
Determine the Gini coefficient and the Lorenz curve of a set of 10 firms selling turnips:

Firm Sold units


A 25
B 4
C 3
D 12
E 17
F 30
G 20
H 17
I 12
J 10

3 (Re)solution
The evaluation of the Gini coefficient involves some manipulations of the data. In particular:

• We add zero to the sold quantities because that is the initial point in the Lorenz curve;
• We operate over the sorted sells because that simplifies the evaluation of the Gini coefficient.

Below we explain the code in detail, what we are doing at each stage.

3.1 Import packages


In this case we will use two packages:

• numpy to work with numerical vectors/arrays, in order to evaluate the Lorenz curve and thus
the Gini coefficient;
• matplotlib to plot the Lorenz curve.

In this case we will follow the convention for both packages:

[1]: import numpy as np


import [Link] as plt

Numerical Methods for Economics Master in Economics


3 (Re)solution 54

3.2 Input data


In this case we will place the information that we had in a list. We take the column with the Sold
quantities and place it in a list called sold.

[2]: # Quantities sold by the firms


sold = [25, 4, 3, 12, 17, 30, 20, 17, 12, 10]

3.3 Prepare the data


[3]: # number of firms
n = len(sold)

# We need to add the zero because that is the initial point in the Lorenz curve
data = [Link](([0], sold))
[Link]()
data

[3]: array([ 0, 3, 4, 10, 12, 12, 17, 17, 20, 25, 30])

3.4 Evaluate the Lorenz curve


[4]: # The Lorenz curve is given by the vectors (x,y)
x = [Link](0, 1, len(data))
y = [Link](data) / [Link](data)

3.5 Display Lorenz curve values


[5]: [Link](list(zip(x, y)))

[5]: array([[0. , 0. ],
[0.1 , 0.02 ],
[0.2 , 0.04666667],
[0.3 , 0.11333333],
[0.4 , 0.19333333],
[0.5 , 0.27333333],
[0.6 , 0.38666667],
[0.7 , 0.5 ],
[0.8 , 0.63333333],
[0.9 , 0.8 ],
[1. , 1. ]])

Numerical Methods for Economics Master in Economics


3 (Re)solution 55

3.6 Plot Lorenz curve


[6]: [Link](x, x, label="Perfect equality")
[Link](x, y, label="Lorenz curve")
# Add legends to plot
[Link]()

[Link]("%firms")
[Link]("%sales")
[Link]("Lorenz curve");

3.7 Evaluate the Gini coefficient


[7]: gini = 2 * [Link](x - y) / n

print(f"The Gini coefficient is {gini:.1%}.")

The Gini coefficient is 30.7%.

Numerical Methods for Economics Master in Economics


56

Notebook 4.4 - Cobb-Douglas


production function
Contents
1 Introduction 57

2 Implementation 57

3 Critical analysis 63

Numerical Methods for Economics Master in Economics


1 Introduction 57

1 Introduction
Consider the Cobb-Douglas production function 𝑌 = 𝐴𝐿𝛼 𝐾 𝛽 where 𝑌 stands for production, 𝐿
labor, 𝐾 capital and the exponents 𝛼 and 𝛽 are, resp., labor and capital elasticity. For each case
draw the production function, assuming A = 1, as well as some isoquants (indifference curves):

1. decreasing returns to scale, 𝛼 = 0.15 and 𝛽 = 0.25;


2. constant returns to scale, 𝛼 = 𝛽 = 0.5;
3. increasing returns to scale, 𝛼 = 0.5 and 𝛽 = 0.75.

2 Implementation
The purpose of this example is to draw the Cobb-Douglas production function for several param-
eters.
In terms of implementation this example will show how to create graphics in a different way
(using the object oriented approach).
We will give examples and hints on the usage of Python graphics for more complex cases like
the three dimensional graphics for the production function or the use of colour maps.
In order to do that we need first to import the required packages.

[1]: import numpy as np


import [Link] as plt
from matplotlib import cm
from [Link] import LinearLocator

Since we are doing a graphical representation we need to set what should be the range where we
want to represent the function.
Sometimes the best way to this is by an trial and error approach, because it is not always obvious
what it should be interesting values. In particular notice that we do not care so much about the
units of both labour and capital.
In this case we decide that we want to draw for values of 𝐿 and 𝐾 between 0 and 3.5. We need
also to determine what is the resolution that we will draw, in this case we use an equally spaced
sequence of size 0.125 (8 points per unit).
For the first figure we set 𝛼 = 0.15 and 𝛽 = 0.25.

[2]: # fig is the figure that can have several plots


# ax is the axes that correspond to a plot in the figure
fig, ax = [Link](subplot_kw={"projection": "3d"})

# Make data: generate the function values using the Cobb Douglas production function
l = [Link](0, 3.5, 0.125)
k = [Link](0, 3.5, 0.125)
L, K = [Link](l, k)
P = L**0.15 * K**0.25

Numerical Methods for Economics Master in Economics


2 Implementation 58

# Plot the surface.


surf = ax.plot_surface(L, K, P, cmap=[Link], linewidth=0, antialiased=False)

# Customize the z axis.


# ax.set_zlim(-1.01, 1.01)
[Link].set_major_locator(LinearLocator(10))

# A StrMethodFormatter is used automatically


[Link].set_major_formatter("{x:.02f}")

# change view angle


ax.view_init(azim=-135)

# Add a color bar which maps values to colors.


[Link](surf, shrink=0.5, aspect=5);

And now the isoquants:

[3]: [Link](l, k, P)

Numerical Methods for Economics Master in Economics


2 Implementation 59

[3]: <[Link] at 0x7fbb3f2996a0>

In the second case we repeat the code above but now for 𝛼 = 0.5 and 𝛽 = 0.5.

[4]: fig, ax = [Link](subplot_kw={"projection": "3d"})

# Make data.
l = [Link](0, 3.5, 0.125)
k = [Link](0, 3.5, 0.125)
L, K = [Link](l, k)
P = L**0.5 * K**0.5

# Plot the surface.


surf = ax.plot_surface(L, K, P, cmap=[Link], linewidth=0, antialiased=False)

# Customize the z axis.


# ax.set_zlim(-1.01, 1.01)
[Link].set_major_locator(LinearLocator(10))
# A StrMethodFormatter is used automatically
[Link].set_major_formatter("{x:.02f}")

Numerical Methods for Economics Master in Economics


2 Implementation 60

# change view angle


ax.view_init(azim=-135)

# Add a color bar which maps values to colors.


[Link](surf, shrink=0.5, aspect=5);

[5]: [Link](l, k, P)

[5]: <[Link] at 0x7fbb3d993d90>

Numerical Methods for Economics Master in Economics


2 Implementation 61

In the third case we repeat the code above but now for 𝛼 = 0.5 and 𝛽 = 0.75.

[6]: fig, ax = [Link](subplot_kw={"projection": "3d"})

# Make data.
l = [Link](0, 3.5, 0.125)
k = [Link](0, 3.5, 0.125)
L, K = [Link](l, k)
P = L**0.5 * K**0.75

# Plot the surface.


surf = ax.plot_surface(L, K, P, cmap=[Link], linewidth=0, antialiased=False)

# Customize the z axis.


# ax.set_zlim(-1.01, 1.01)
[Link].set_major_locator(LinearLocator(10))
# A StrMethodFormatter is used automatically
[Link].set_major_formatter("{x:.02f}")

# change view angle

Numerical Methods for Economics Master in Economics


2 Implementation 62

ax.view_init(azim=-135)

# Add a color bar which maps values to colors.


[Link](surf, shrink=0.5, aspect=5);

[7]: [Link](l, k, P)

[7]: <[Link] at 0x7fbb3d783110>

Numerical Methods for Economics Master in Economics


3 Critical analysis 63

3 Critical analysis
This solves the problem but it is not ideal because we are repeating the same code over and over
again. And each time that we copy and pasting we risk to introduce errors.
The best strategy in this case would be to see what is common and what is different and place that
code that is common in a function. This is known as the DRY “Do not Repeat Yourself” principle.
Some possible alternatives that are left as an exercise for the reader are:

• to create a Cobb Douglas function that uses 𝛼 and 𝛽 as arguments in order to return the
production from labour and capital.
• to create a function that given a production function plots the contour nd 3-D plots.

In particular these generalizations will be dealt in the next module.

Numerical Methods for Economics Master in Economics

You might also like