Python Programming for Economics
Python Programming for Economics
Contents
1 Introduction 3
1.1 Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.1 Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.2 Computer programming . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Programming languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.1 Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.2 Main concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4 Classification of programming languages . . . . . . . . . . . . . . . . . . . . . 7
2 Python 8
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.2 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.2.1 The Pythonic way . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.2.2 Python identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2.3 Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.2.4 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.3 Data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.3.1 Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.3.2 Built-in types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.3.3 Data structure example . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.4 Control flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.4.1 Basic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.4.2 Advanced . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.5 Builtin functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.6 Standard library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3 Code organization 20
3.1 Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.2 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Contents 2
5 Exercises 28
1 Introduction
1.1 Concepts
1.1.1 Algorithms
What it is?
Computer programming
or coding is the composition of sequences of instructions, called programs, that computers
can follow to perform tasks. It involves designing and implementing algorithms, step-by-step
specifications of procedures, by writing code in one or more programming languages.
Source: [Link]
The book is one of the most influential computer science books of its time and, like Wirth’s
other work, has been used extensively in education.
Source: [Link]
What is programming
Programming corresponds to the task of creating code:
• That means to put in code a given algorithm with the purpose to solve the problems we
are interested.
• That implies to organize the code in appropriate chunks/blocks. Those blocks, usually
correspond to functions and modules/packages.
• We also control the program flow, that means that the same code can take different paths
depending on its input.
Programming languages
The basic concepts
of a computer language are:
• its structure;
• the data types;
• the libraries.
Language structure
• syntax and grammar (that corresponds to the form);
• semantics (the meaning);
• control flow;
• code organization (functions, modules/packages/libraries).
Data types
How the different types of data are represented in the languages:
• numbers;
• text;
• tables;
• lists;
• etc.
Libraries
Refer to how other information can be found:
• contain data types and/or functions (algorithms);
• usually deal with a specific task;
• are organized as packages or modules (organizational difference only);
Classification:
• standard library (builtin/are guaranteed to be there);
• external ecosystem.
1.3 Examples
Example of programming languages
There are lots of computer languages. In the scope of this course some of the most widely
used are:
• Python;
• R;
• Julia;
• Matlab/Octave.
In this course we will focus our study on the Python programming language.
R
R is, just as Python, a computer language widely used in Data Analysis but in also in other
more general areas like Computational Economics or Computational Finance.
Just like Python it has a very rich, diverse and capable ecosystem of packages. The language’s
origin are in the Data Analysis. Examples of packages used to hold, and then explore data are:
• DataFrame;
• [Link];
Due to the time constraints in this course we present a brief introduction to R in one of the
notebooks.
Julia
Due to the time constraints in this course we present a brief introduction to Julia in one of the
notebooks.
logic are designed so that the software, rather than the programmer, decides what order in
which the instructions are executed;
object oriented have as the main characteristics: data abstraction, inheritance, and dynamic
dispatch.
The same language can fall into several of these categories with varying degrees of support for
each of them. So, for example, both Python, R and Julia (the original trio that gave the name
to Jupyter) support imperative, functional and object oriented styles.
2 Python
2.1 Introduction
Python programming language
[Link]
History
2.2 Syntax
2.2.1 The Pythonic way
Python philosophy
• The number of functions that is always available, when a program starts (built-in), is
quite small. This is a design choice, all the other functions and data types that come
with Python are available in packages or modules.
[Link]
Python philosophy
When we speak a human language there is a natural way to tell things, the idiomatic ex-
pressions. The same happens for Python, that is called the Pythonic way.
Python’s motto
is “Make simple things simple and complex things possible”.
There are several principles that are the core of python language like this.
• Try import this in your shell and see what the result is.
Identifiers
Python identifiers correspond to names.
Examples of identifiers are:
• keywords:
for example def or return;
• variables;
• function names;
• module names:
for example import pandas as pd - pandas and pd are identifiers.
Example (function)
def colatz(n):
"this implements the function from the Colatz conjecture"
if n % 2 == 0: # n is even
return n//2 # // corresponds to the integer division
else: # n is odd
return 3*n+1
variables: n;
2.2.3 Keywords
Reserved keywords
Operators
Note that some of the keywords are actual operators:
• and
• in
• is
• not
• or.
Values
In the keywords we have also values (those are easy to identify since they are the only ones
capitalized):
• False
• True
• None
2.2.4 Operators
Examples
comparison: ==, !=, <, >, <=, >=, is, is not, in and not in;
Definition
Data types
In computer science and computer programming, a data type (or simply type) is (all at once):
[Link]
Data structures
A particular case of data types are:
Data structures
Some (data) types are very useful for storing and retrieving data and are called data structures.
One of the important features is the ease and efficiency that the data can be accessed and
updated.
[Link]
Sequences
A data structure is a sequence if we can browse its content in a sequential way. For example
lists, strings, tuples and tables are examples of sequences.
We are interested in these data structures to work with real world data. In the next couple
of modules we will introduce and deal with them.
Some of the more important data structures that are interested are:
• lists;
• records (tuples);
• tables.
Source: [Link]
The purpose of this chart is just to show that there are relations between the standard types.
• The standard data types are builtin, that is they come directly with the installed Python,
and can be used immediately.
• Numbers;
• Modules.
• in the Python standard library (provides an extensive list of specialized data types);
• in external libraries (like the Scientific Python ecosystem that provide valuable data
types to work on practical problems).
Data types
• list - lists;
• tuple - tuples.
Birthday: dates/[Link]
E.g. [Link](1999,10,12)
Erasmus: Boolean/bool
There are only two possible values: {F, T }
Control flow
Definition
In computer science, control flow (or flow of control) is the order in which individual state-
ments, instructions or function calls of an imperative program are executed or evaluated.
[Link]
Choice: Loops:
Examples
# Condition-controlled
n, prod = 1, 1
while prod < 1e100:
n += 1 # augmented assignment, the same as: n = n + 1
prod *= n # the same as above but now for multiplication
print(n, prod)
# Count/collection-controlled
prod = 1
for i in range(1, n+1):
prod *= i
print(prod)
2.4.2 Advanced
Advanced
Non-local control flow:
• exceptions;
• generators;
• asynchronous I/O.
Exception example
def inverse(n):
return 1/n
def half_inverse(n):
w = inverse(n)
print("inverse concluded")
return 2*w
def try_dvision(n):
try:
z = half_inverse(n)
except ZeroDivisionError:
print ("Can not divide by zero")
Data types
Of those functions that are builtins some are related with the standard data types that we
saw already:
• bool - for boolean values; • int - integer numbers;
Generic functions
From the built-in functions, that do not correspond to data types, others are generic func-
tions that operate on some or all of the data types defined above:
Rather than building all of its functionality into its core, Python was designed to be
highly extensible via modules. This compact modularity has made it particularly
popular as a means of adding programmable interfaces to existing applications.
Van Rossum’s vision of a small core language with a large standard library and
easily extensible interpreter stemmed from his frustrations with ABC, which es-
poused the opposite approach.
[Link]
The components from the standard library can be accessed using the import statement, just
like any external packages. The only difference regarding external packages is that if Python
is properly installed we can be sure that those packages are always available.
In Python the standard library is quite extensive.
Documentation
All the documentation regarding the Python standard library can be found in its site:
Examples
Types of packages in the standard library (there are more):
3 Code organization
3.1 Code
What is a program?
• A piece of code that does a given task;
• Where is it (in the case of Python/R/Julia)?
– in the code cells of a Jupyter notebook;
– in an external file, that in the particular case of these languages is called a script.
3.2 Functions
3.2.1 Purpose of functions
Example
def format_name(first_name, last_name, middle_name=None):
"""
Formats a full name with optional middle name.
Args:
first_name: The first name.
last_name: The last name.
middle_name: (Optional) The middle name.
Returns:
The formatted full name.
"""
if middle_name:
return f"{first_name} {middle_name} {last_name}"
else:
return f"{first_name} {last_name}"
• Functions accept input arguments and return output arguments (clearly define its role);
• Internal variables are local to the function (no pollution of the workspace);
• Functions allow for better testing since the code is a single place, and the test can be
thoroughly applied.
3.2.2 Parameters
Classification
The way we pass and receive argument is flexible and simple.
We can classify the different types of arguments based on:
Warning
Its use is pervasive on all the functions of the standard library as well as external libraries that
we use.
Passing modes
There are, basically, two ways to pass arguments to functions:
Position the argument is determined based on the order it is passed (first, second, ...);
Keyword the argument has a name that refers explicitly to the name of that argument.
Note
Positional arguments always come first while keyword arguments always come last.
For readability and performance, it makes sense to restrict the way arguments can be passed
so that a user needs only to look at the function definition to determine if items are passed by
position, by position or keyword, or by just by keyword.
Further documentation:
• [Link]
• [Link]
• [Link]
3.3 Modules/packages
What is the best way to organize the code? (2: modules)
Modules
• If a function is used in many different places it should be placed into a module;
• In Python that means an external file where the code is placed and from where it can
be used by importing it;
• A regular module is thus enclosed within a file.
So even although technically packages and libraries refer to different concepts, they are so
closely related that is usual to use both terms interchangeably.
Not only that but the Python type for both modules and packages is just module.
A simple rule
is then that we install libraries and import packages and modules.
• store the code such that it is organized and if possible place it in functions;
• even if a data type can be expanded at will always define its dimension in advance;
• make your code able to work with scalar and vectors from the beginning;
• numpy defines multidimensional arrays that are suitable for high performance calcula-
tions while at the same time providing a nice interface;
• matplotlib provides the features required to produce high quality graphics. Since it
uses numpy objects internally it is a natural match to work with the previous packages;
• pandas provides features to work with tables that are not all necessarily numeric. Pro-
vides a nice interface to easily work, transform and display tabular data. It is built on
top of/uses numpy and matplotlib.
All these packages are the building blocks used by more specific packages that are built on top
of them.
4.3 Numpy
numpy
Numpy sets the basis for working with large quantities of numbers in Python.
The purpose of this is also in the simplicity and efficiency of operations:
• Its functions are universal, i.e. they apply element by element:
Example: [Link]([Link]([1,2,3])) -> [Link]([exp(1),exp(2),exp(3)])
• Numerical arrays support broadcasting, i.e. where possible they expand automatically
to make operations possible:
Example: 1 + [Link]([1,2,3]) -> [Link]([2,3,4])
numpy modules
In order to avoid having everything in the main module there are several modules for spe-
cific tasks. Some that we will be using are:
• [Link] for the most common and efficient linear algebra operations (for vector,
matrices, tensors).
4.4 Scipy
scipy
scipy complements Numpy with operations that are useful for scientific computing/computa-
tional economics operations. It is package that has in one place several modules/sub-packages
that are useful in simulation:
[Link] for numerical integration of functions and of differential equations;
[Link] for numerical optimization (finding minimum and maximum) or finding ze-
ros of functions;
[Link] generates random numbers following a standard normal distribution (mean and
standard deviation are parameters);
For a more complete list of supported distributions consult both Numpy and Scipy documen-
tation.
4.5 Conclusion
Mastery implies practice: practical motivation analogy
It is knot a problem
Knots can be either decorative or practical. In practice:
• Knot tying skills are often transmitted by sailors, scouts, climbers, canyoners, cavers,
arborists, rescue professionals, stagehands, fishermen, linemen and surgeons.
Taking some artistic freedom we could say that data types are the statistics and programming
knots. And so all the previous considerations about knots apply with the corresponding equiv-
alencies.
5 Exercises
Python functions
2. Write a function that evaluates the mean of the values of a vector by using the available
function sum.
How do the results compare with the statistical function [Link]? Does this code works
with matrices?
3. Write a function that evaluates the mean, median and standard deviation from the val-
ues of a vector.
1. Suppose that you intend successively to divide π by 2. What is the largest term in this
succession that is smaller or equal to 0.01?
What is the smaller ratio that is larger than 0.01?
2. Create a function that generates an Hilbert matrix of order m ∗ n. The Hilbert matrix is
H = [hij ] , i = 1..m, j = 1..n such that
1
hij = .
i+j−1