Python for Finance
UCEMA 2023
Pablo A Macri 1
Syllabus
Lecture 1
Why Python
How to run scripts: REPL, IDE’s, and IPython
notebooks
Basic data types, names, operators and
expressions. Built-in functions.
Lecture 2
Conditionals
Iterators and definite/indefinite Iterations.
Composite data types: strings, lists, tuples,
dictionaries and sets.
Pablo A Macri 2
Syllabus
Lecture 3
Abstraction and decomposition. Functions.
Classes*.
NumPy
Lecture 4
Matplotlib
Pandas
*wishful inclusion
Pablo A Macri 3
Lectures Structure
1st block
~1h: Presentation of subjects + code explanation.
~15’: Discussion + Q&A.
2nd block
~1h: Presentation of subjects + code explanation.
~15’: Discussion + Q&A.
Pablo A Macri 4
Iterations
Composite data types
Indefinite Iterations
break clause
continue clause
else clause
Infinite loops
Definite Iterations
Pablo A Macri 5
Composite Data Type
There are number of non-scalar data types: strings, lists, tuples,
dictionaries and sets
Indexable
>>>name = "eric"
e r i c
0 1 2 3
Pablo A Macri 6
Control Flow: Iterations
Iteration means executing the same block of code
over and over, potentially many times. A programming
structure that implements iteration is called a loop.
In programming, there are two types of iteration,
indefinite and definite:
With indefinite iteration, the number of times the loop is
executed isn’t specified explicitly in advance. Rather, the
designated block is executed repeatedly as long as some
condition is met.
With definite iteration, the number of times the designated
block will be executed is specified explicitly at the time the
loop starts.
Pablo A Macri 7
while Loops
The format of a rudimentary while loop is
When a while loop is encountered, <expr> is first evaluated in
Boolean context
if <expr> is True, do all the steps inside the while code block
check <expr> again
repeat until <expr> is False
The controlling expression <expr>, typically involves one or
more variables that are initialized prior to starting the loop and
then modified somewhere in the loop body.
Pablo A Macri 8
while Loops
Consider the loop on the right. Here’s what’s
happening :
n is initially 5. The expression in the while
statement header on line 2 is n > 0, which is True,
so the loop body executes. Inside the loop body on
line 3, n is decremented by 1 to 4, and then
printed.
When the body of the loop has finished, program execution returns to
the top of the loop at line 2, and the expression is evaluated again. It is
still true, so the body executes again, and 3 is printed.
This continues until n becomes 0. At that point, when the expression is
tested, it is false, and the loop terminates. Execution would resume at
the first statement following the loop body, but there isn’t one in this
case.
Pablo A Macri 9
break and continue Statements
In each example we have seen so far, the
entire body of the while loop is executed
on each iteration. Python provides two
keywords that terminate a loop iteration
prematurely:
The break statement immediately terminates
a loop entirely. Program execution proceeds to
the first statement following the loop body.
The continue statement immediately
terminates the current loop iteration. Execution
jumps to the top of the loop, and the controlling
expression is re-evaluated to determine
whether the loop will execute again or
terminate.
Pablo A Macri 10
while Loops
Here’s a script file called break.py The next script, continue.py, is
that demonstrates the break identical except for a continue
statement statement in place of the break
Running break.py from a The output of continue.py looks
command-line interpreter produces like this
the following output
Pablo A Macri 11
The else Clause
Python allows an optional else clause at the end of a while loop
The <additional_statement(s)> specified
in the else clause will be executed when the while
loop terminates
What would be the difference with the code below?
Here, without the else clause,
<additional_statement(s)> will be executed
after the while loop terminates, no matter what.
When <additional_statement(s)> are placed
in an else clause, they will be executed only if the
loop terminates “by exhaustion”—that is, if the loop
iterates until the controlling condition becomes false.
Pablo A Macri 12
The else Clause
Consider the following example Now observe the difference here
In this case, the loop repeated until This loop is terminated prematurely
the condition was exhausted: n with break, so the else clause isn’t
became 0, so n > 0 became False. executed.
Because the loop ended, the else
clause was executed.
Pablo A Macri 13
The else Clause
When might an else clause on a while loop be useful? One
common situation is if you are searching a list for a specific
item. You can use break to exit the loop if the item is found,
and the else clause can contain code that is meant to be
executed if the item isn’t found
Pablo A Macri 14
Infinite Loops
Suppose you write a while loop that theoretically never ends
This code was terminated by <ctrl>+c, which generates an
interrupt from the keyboard. Otherwise, it would have gone on
unendingly
Pablo A Macri 15
Infinite Loops
You can end an infinite loop You can also specify multiple
using a break sentence break statements in a loop
when there are multiple
reasons to end the loop, it is
When a becomes empty, often cleaner to break out from
not a becomes True, and several different locations,
the break statement exits rather than try to specify all the
the loop. termination conditions in the
loop header.
Pablo A Macri 16
Nested while Loops
A while loop can be A break or continue
contained within another statement found within nested
while loop loops applies to the nearest
enclosing loop
Pablo A Macri 17
Nested while Loops
while loops can be nested inside if/elif/else statements
and vice versa
Pablo A Macri 18
One-Line while Loops
As with an if statement, a while loop can be specified on
one line. If there are multiple statements in the block that
makes up the loop body, they can be separated by semicolons
As mentioned previously, PEP 8 discourages multiple
statements on one line.
Pablo A Macri 19
Definite Iterations: for Loops
Python’s for loop looks like this
<iterable> is a collection of objects—for example, a string, list,
tuple, set, dictionary, etc. The <statement(s)> in the loop body
are denoted by indentation, and are executed once for each item in
<iterable>. The loop variable <var> takes on the value of the
next element in <iterable> each time through the loop.
Here is a representative example
Pablo A Macri 20
The range() function
If you wanted to iterate through the values from 0 to 4, you can simply do
this
If the number range were much larger,
it would become unpractical.
Python provides the built-in range() function, which returns an iterable
that yields a sequence of integers.
range(<end>) returns an iterable that yields integers starting with 0, up to
but not including <end>
Note that range() returns an
object of class range. Because a range
object is an iterable, you can obtain
the values by iterating over them
with a for loop
Pablo A Macri 21
range(start, stop, step)
By default, values start at start=0 and
step=1
It cycles until the value stop-1
Pablo A Macri 22
break and continue
break terminates the loop completely and proceeds to the
first statement following the loop
continue terminates the current iteration and proceeds to
the next iteration
Pablo A Macri 23
The else Clause
The else clause will be executed if the loop terminates through
exhaustion of the iterable
The else clause won’t be executed if the list is broken out of with a
break statement
Pablo A Macri 24
while vs for Loops
for loops while loops
known number of unbounded number of
iterations iterations
can end early via break can end early via break
uses an iterator can use a counter but
must initialize before loop
and increment it inside
loop
can rewrite a for loop may not be able to rewrite
using a while loop a while loop using a for
loop
Pablo A Macri 25
Strings
Strings objects
Immutability
Slicing
String operators
String built-in functions
String built-in methods
Pablo A Macri 26
Strings
Strings are sequences of character data
The string type in Python is called str
String literals may be delimited using
either single or double quotes
A string in Python can contain as many
characters as you wish. A string can also
be empty
If you want to include either type of quote character within the
string, just delimit the string with the other type
Pablo A Macri 27
Triple-Quoted Strings
Triple-quoted strings are delimited by matching groups of three
single quotes or three double quotes. Escape sequences still
work in triple-quoted strings, but single quotes, double quotes,
and newlines can be included without escaping them
Pablo A Macri 28
String Operators
Concatenation operator +
Replication operator *
Pablo A Macri 29
Data Input: input
Prints what's in quotation marks
The user types something and press <enter>
The functions return the input sequence
You can bind the returned value to a variable
input returns a string and therefore should
be casted if you want to work with numbers
Pablo A Macri 30
String Operators
in operator. Returns True if the first operand is contained
within the second, and False otherwise
There is also a not in operator
Pablo A Macri 31
Built-in String Functions
f
Examples:
Computers store all information as numbers. The simplest
(Latin characters) scheme to represent character data is ASCII.
Unicode is an ambitious standard to provide a numeric code
for every possible character, in every possible language
Pablo A Macri 32
String Indexing
Individual characters in a string can be accessed by specifying
the string name followed by a number in []
Indexing in Python is zero-based: the first character in the
string has index 0, the last character will be the length of the
string minus one
Pablo A Macri 33
Cycling over the value or the index
Iteration over the index of the string
Iteration over the elements of the string
Pablo A Macri 34
String Slicing
If s is a string, an expression of the form s[m:n] returns the
portion of s starting with position m, and up to but not
including position n
returns a substring
that is n - m omitting both indices
characters in length returns the original
string
s[:m] and s[0:m]
are equivalent If the first index in a slice is
greater than or equal to the
second index, Python returns
an empty string
s[:n] + s[n:]
will be equal to s
Pablo A Macri 35
Stepping the slice
a third index designates a step
You can specify a negative step. In that case, the starting/first
index should be greater than the ending/second index
5:0:-2 means “start at the usual way for reversing a string
last character and step
backward by 2, up to but not
including the first character.”
Pablo A Macri 36
Modifying Strings
Strings can’t be modified, in Python they are immutable objects
But you can generate a copy of the original string that has the
desired change in place
There is also a built-in string method to do this
Pablo A Macri 37
Built-in String Methods
Methods are functions defined for certain type of objects
(more on this in the OOP Lecture)
<args> specifies the arguments passed to the method (if any)
Case Conversion
s.capitalize() returns a copy of s with the first character
converted to uppercase and all other characters converted to
lowercase
s.lower() returns a copy of s with all alphabetic
characters converted to lowercase
s.swapcase() returns a copy of s with uppercase
alphabetic characters converted to lowercase and vice
versa
Pablo A Macri 38
Built-in String Methods
String Formatting
s.zfill(<width>) returns a copy of s left-padded with '0'
characters to the specified <width>. If s contains a leading sign, it
remains at the left edge of the result string after zeros are inserted. If s
is already at least as long as <width>, it is returned unchanged
++ huge amount of other methods…
(Almost) all string methods can be accessed using dir
https://docs.python.org/3/library/stdtypes.html#string-methods
Pablo A Macri 39
Python String Formatting
Let’s assume you’ve got the following variables
Based on these variables, you’d like to generate an output
string containing a simple error message
There are 4 ways for string formatting
“Old Style” String Formatting (% Operator)
“New Style” String Formatting (str.format)
String Interpolation / f-Strings (Python 3.6+)
Template Strings (Standard Library)
Pablo A Macri 40
“Old Style” String Formatting
With string operands, the modulo operator has an entirely
different function: string formatting.
Here’s what the syntax of the string modulo operator looks like:
On the left side of the % operator, <format_string> is a
string containing one or more conversion specifiers. The
<values> on the right side get inserted into
<format_string> in place of the conversion specifiers. The
resulting formatted string is the value of the expression.
Pablo A Macri 41
“Old Style” String Formatting
Here’s a print() statement that displays a formatted string
using the string modulo operator
In addition to representing the string modulo operation itself,
the '%' character also denotes the conversion specifiers in the
format string—in this case, '%d', '%s', and '%.2f'.
In the output, each item from the tuple is converted to a string
value and inserted into the format string in place of the
corresponding conversion specifier:
The first item in the tuple is 6, a numeric value that replaces '%d' in the
format string.
The next item is the string value 'bananas', which replaces '%s'.
The last item is the float value 1.74, which replaces '%.2f'.
Pablo A Macri 42
“Old Style” String Formatting
If there are multiple values to insert, then they must be
enclosed in a tuple as illustrated before. If there is only one
value, then it can appear by itself
Notice also that string modulo operation isn’t only for printing.
You can also format values and assign them to another string
variable
Pablo A Macri 43
“Old Style” String Formatting
Conversion specifiers appear in the <format_string> and
determine how values are formatted when they’re inserted.
A conversion specifier begins with a % character and consists of
these components:
%[<flags>][<width>][.<precision>]<type>
% and <type> are required. The remaining components
shown in square brackets are optional.
Pablo A Macri 44
“Old Style” String Formatting
The conversion type is the last component of the conversion
specifier
%[<flags>][<width>][.<precision>]<type>
It determines the type of conversion the corresponding value
undergoes before insertion into the format string
Pablo A Macri 45
“New Style” String Formatting
You can use format() to do simple positional formatting, just
like you could with “old style” formatting
Or you can refer to your variable substitutions by name and use
them in any order you want. This is quite a powerful feature as
it allows for re-arranging the order of display without changing
the arguments passed to format():
This also shows that the syntax to format an int variable as a
hexadecimal string has changed. Now you need to pass a
format spec by adding a :x suffix
Pablo A Macri 46
String Interpolation / f-Strings
This new way of formatting strings lets you use embedded
Python expressions inside string constants
This prefixes the string constant with the letter “f“—hence the
name “f-strings.” You can embed arbitrary Python expressions
String literals also support the existing format string syntax of
the str.format() method
Pablo A Macri 47
Python
An ultra-crash course
Pablo A Macri 48
Lists
Python Lists
Lists Are Ordered
Lists Can Contain Arbitrary Objects
List Elements Can Be Accessed by Index
Lists Can Be Nested
Lists Are Mutable
Lists Are Dynamic
Lists in Loop Context
List Comprehensions
Pablo A Macri 49
Python Lists
A list is a collection of arbitrary objects.
Lists are defined in Python by enclosing a comma-separated
sequence of objects in square brackets []
The important characteristics of Python lists are:
Lists are ordered.
Lists can contain any arbitrary objects.
List elements can be accessed by index.
Lists can be nested to arbitrary depth.
Lists are mutable.
Lists are dynamic.
Pablo A Macri 50
Lists are ordered
A list is not merely a collection of objects. It is an ordered
collection of objects. The order in which you specify the
elements when you define a list is an innate characteristic of
that list and is maintained for that list’s lifetime.
Lists that have the same elements in a different order are not
the same:
Pablo A Macri 51
Lists Can Contain Arbitrary Objects
The elements of a list
can all be the same type
Or the elements can be
of varying types
Lists can even contain
complex objects, like
functions, classes, and
modules (Don’t
desperate if you don’t
know about them yet!!!)
Pablo A Macri 52
Lists Can Contain Arbitrary Objects
A list can contain any
number of objects,
from zero to as many as
your computer’s
memory will allow.
List objects needn’t be
unique.
Pablo A Macri 53
List Elements Are Indexed
Individual elements in a list can be accessed using an index in
square brackets. This is exactly analogous to accessing
individual characters in a string. List indexing is zero-based as it
is with strings.
Here is Python code Negative list
to access some index counts from
elements of a the end of the list
Virtually everything
about string indexing
works similarly for
lists
Pablo A Macri 54
Slicing Lists
Slicing also works. If a is a list, the expression a[m:n] returns
the portion of a from index m to, but not including, index n
Both positive and negative
indices can be specified.
Omitting the first index starts
the slice at the beginning of
the list, and omitting the
second index extends the slice
to the end of the list
Pablo A Macri 55
List Elements Are Indexed
You can specify a stride,
either positive or negative
The syntax for reversing a list
works the same way it does
for strings
Pablo A Macri 56
List vs Strings in [:]
The [:] syntax works for lists.
However, there is an important
difference between how this
operation works with a list and how
it works with a string. If s is a string,
s[:] returns a reference to the
same object.
Conversely, if a is a list, a[:]
returns a new object that is a copy
of a
Pablo A Macri 57
List Operators
Several Python operators and built-in functions can also be
used with lists in ways that are analogous to strings
The in and not in operators
The concatenation + and replication * operators
Pablo A Macri 58
List Built-In Functions
The len(), min(), and max() functions
Pablo A Macri 59
Lists Can Be Nested
An element in a list can be any sort of object. That includes
another list and so forth to arbitrary depth.
x[0], x[2], and x[4] are strings, each one character long
But x[1] and x[3]
are sublists
Pablo A Macri 60
Lists Can Be Nested
To access the items in x[1][1] is yet
a sublist, simply another sublist, so
append an additional adding one more
index index accesses its
elements
All the usual syntax
regarding indices
and slicing applies
to sublists as well
Pablo A Macri 61
List Can Be Nested
Operators and functions apply to only the list at the level you
specify and are not recursive
Pablo A Macri 62
Lists Are Mutable
Scalar types (int, float, bool, etc.) are immutable,
meaning that they can’t be changed once they have been
assigned. It doesn’t make much sense to think of changing the
value of an integer. If you want a different integer, you just
assign a different one.
By contrast, the string type is a composite type. Strings are
reducible to smaller parts—the component characters. It might
make sense to think of changing the characters in a string. But
you can’t. In Python, strings are also immutable.
The list is the first mutable data type you have encountered.
Once a list has been created, elements can be added, deleted,
shifted, and moved around at will. Python provides a wide
range of ways to modify lists.
Pablo A Macri 63
Modifying a Single List Value
A single value in a list can be replaced by indexing and simple
assignment
You can’t do this with a string:
A list item can be deleted with the del command
Pablo A Macri 64
Methods That Modify a List
String methods do not modify the target string directly. That is
because strings are immutable. Instead, string methods return
a new string object that is modified as directed by the method.
They leave the original target string unchanged
List methods are different. Because lists are mutable, the list
methods shown here modify the target list in place.
Pablo A Macri 65
Methods That Modify a List
a.append(<obj>) appends object <obj> to the end of list a
List methods modify the target list in place. They do not return a
new list
Pablo A Macri 66
Lists Are Dynamic
When items are added to a list, it grows as needed
Similarly, a list shrinks to accommodate the removal of items
Pablo A Macri 67
Other List Operations
.sort() and sorted()
.reverse()
And many more
https://docs.python.org/3/tutorial/datastructures.html
L = [9, 6, 0, 3]
sorted(L) returns a sorted list, does not mutate L
L.sort() mutates L a [0, 3, 6, 9]
L.reverse() mutates L a [9, 6, 3, 0]
Pablo A Macri 68
Iterating over a List
Ex: compute the sum of elements of a list
Is possible to iterate over list elements directly
Notice
List elements are indexed from 0 to len(L)-1
range(n) goes from 0 a n-1
Pablo A Macri 69
List Comprehension
This is how a list comprehension looks like
It is a one-liner of a full for loop structure
Pablo A Macri 70
Tuples
Python Tuples
Defining Tuples
Using Tuples
Tuple Assignment
Tuples are immutable
Pablo A Macri 71
Python Tuples
A tuple is a ordered
collection of arbitrary
objects.
Tuples are defined in
Python by enclosing a
comma-separated
sequence of objects in
parentheses()
Tuples are immutable
Pablo A Macri 72
Python Tuples
Why use a tuple instead of a list?
Program execution is faster when manipulating a tuple than it is for the
equivalent list. (This is probably not going to be noticeable when the list
or tuple is small.)
Sometimes you don’t want data to be modified. If the values in the
collection are meant to remain constant for the life of the program,
using a tuple instead of a list guards against accidental modification.
There is another Python data type that you will encounter shortly called
a dictionary, which requires as one of its components a value that is of
an immutable type. A tuple can be used for this purpose, whereas a list
can’t be.
Pablo A Macri 73
Python Tuples
In a shell session, you can
display the values of several
Interpreted as a tuple
objects simultaneously by
entering them directly
separated by commas
There is no ambiguity when
defining an empty tuple,
nor one with two or more
elements
But what happens when
Trailing comma is
you try to define a tuple mandatory here
with one item
Pablo A Macri 74
Swapping Variables
Frequently when programming,
you have two variables whose
values you need to swap. In most
programming languages, it is
necessary to store one of the
values in a temporary variable
while the swap occurs like this
In Python, the swap can be done
with a single tuple assignment
Pablo A Macri 75