0% found this document useful (0 votes)
9 views87 pages

UCEMA2024 Python Lecture1

The document outlines a syllabus for a Python for Finance course at UCEMA in 2023, detailing lectures on Python fundamentals, data types, and libraries like NumPy and Pandas. It emphasizes the popularity of Python due to its open-source nature, multi-paradigm capabilities, and ease of use across various platforms. The course includes practical sessions using tools like Jupyter notebooks and IDEs for coding and data analysis.

Uploaded by

Manuel A
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)
9 views87 pages

UCEMA2024 Python Lecture1

The document outlines a syllabus for a Python for Finance course at UCEMA in 2023, detailing lectures on Python fundamentals, data types, and libraries like NumPy and Pandas. It emphasizes the popularity of Python due to its open-source nature, multi-paradigm capabilities, and ease of use across various platforms. The course includes practical sessions using tools like Jupyter notebooks and IDEs for coding and data analysis.

Uploaded by

Manuel A
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
You are on page 1/ 87

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
Python
An ultra-crash course

Pablo A Macri 5
Welcome to Python
Why Python
Language features
Pros and Cons
Running Python
Shell or REPL
Interactive Python
Jupyter notebooks
IDEs

Pablo A Macri 6
A Computer Program
Sequence of instructions stored inside computer
built from predefined set of primitive instructions
• arithmetic and logic
• simple tests
• moving data
programs execute each instruction in order
use tests to change the flow through sequence
stop when done
Programs are coded in a two kind of programming languages
Interpreted
Python
languages

Compiled
languages

Pablo A Macri 7
Python Programming Language
The programming language was started as a
side project by Dutch programmer Guido van
Rossum. In the late 1980s, van Rossum was
working on a distributed system at the
Centrum Wiskunde & Informatica (CWI), the
Dutch national research center for math and
computer science Guido van Rossum in 2001,
the year the Python Software
Frustrated by the inadequacies of existing Foundation was established

programming languages, he decided to create a


new one — one that would be both easy-to-
use and capable to get things done swiftly
BTW, Python has nothing to do with the snake
Monty Python (also collectively
known as the Pythons) are a
British surreal comedy group

Pablo A Macri 8
Popular Programming Languages
Java: server-side web apps, video games, mobile apps
JavaScript: client-side, servers-side web apps
C++: SOs, video games, heavy applications
PHP: server-side apps
Python: multipurpose!!
Ruby: server-side apps
C#: Windows desktop apps
SQL: databases

Pablo A Macri 9
More comparisons

The views of Python questions on Stack Overflow, US and global search-engine popularity relative to other
programming languages reflects the huge growth in Python users.

Pablo A Macri 10
Comparisons with other languages
The TIOBE Programming Community index is an indicator of the popularity
of programming languages

Pablo A Macri 11
Companies that Heavily use Python

Pablo A Macri 12
Why Python is so popular?
Open-source: the language and its libraries are redistributable and
openly available.

Multi-paradigm: can implement several programing paradigms as


object oriented, imperative, procedural, functional programing and more.

Multi-purpose: can be used from fast and interactive


developments, to big applications, from low to high level analytic systems.

Multi-platform: available in all operating systems like Windows,


Linux, y Mac OS; can be run on a desktop machine, web servers, big clusters
and the cloud; can be used even in small devices as Raspberry Pi.

Dynamical Types: data types are not declared in Python. Instead,


they are inferred dynamically from context in execution time.

Pablo A Macri 13
Why Python is so popular?
Indentation: Python uses indentation to define coding blocks
providing full program structure at glance.

Garbage Collector: Python frees automatedly memory no longer


used by the program.

Language Philosophy: Just type import this


PEP 20 -- The Zen of Python

Pablo A Macri 14
Installing Python
ANACONDA distribution is readily available within the
client’s system. This will be the course’s official Python
distribution.

If you need help getting it installed, please let me


know.

You may have other installations; ask in case you don’t


find an equivalent tool to the ones discussed here

https://www.anaconda.com/download
Pablo A Macri 15
Installing Python

https://docs.anaconda.com/anaconda/install/verify-install/
Pablo A Macri 16
ANACONDA Navigator

Pablo A Macri 17
Python Shell or REPL
Just type Python in the ANACONDA Prompt

Entered code expires with the session


https://docs.anaconda.com/anaco
Makes sense only for small testing nda/install/verify-install/

Quit Python typing exit() or <ctrl>+z


This is know as a Python shell or REPL for read-eval-print loop
Pablo A Macri 18
From Console
Console is also useful for launching code to run. In your favorite
editor, write the following lines and save as script0.py

Now in the console run Python script0.py

Pablo A Macri 19
Interactive Python

Pablo A Macri 20
Interactive Python

Pablo A Macri 21
Interactive Python within Spyder
Launch Spyder from the ANACONDA Navigator

Pablo A Macri 22
Interactive Python within Spyder
There is an IPython console on the bottom right

Pablo A Macri 23
Interactive Python
Beyond Python code, there are some helpful commands in IPython
Command Description
? Introduction and overview of IPython’s features
%quickref Quick reference
help() Python’s own help system
object? Details about object, use object?? for extra
details

Tab completion: type object.<TAB> to view the object’s attributes


History: using up and down arrows
Magic functions
Functions that work with code: %run, %edit, %save, %macro, %recall
Functions which affect the shell: %colors, %xmode, %autoindent,
%automagic
Other functions such as %reset, %timeit, %%writefile, %load, %paste

Pablo A Macri 24
IDEs
Is painful to just type things into a shell
Much better to have an integrated development
environment (IDE)
PyCharm, Eclipse, VS Code, Atom, IDLE or Spyder are a
few examples
IDEs come with
Text editor – use to enter, edit and save your programs
Shell – place in which to interact with and run your
programs
Debugger – to find and correct bugs

Pablo A Macri 25
Spider IDE

Pablo A Macri 26
Spyder Components

Pablo A Macri 27
More Spyder Features
Watch out! In newer versions, persistence before
execution and cross persistence has been eliminated.
Object persistence after execution Persistence after execution remains though.

Object persistence before execution might have undesirable effects.


See this example:
First, we run the code script3.py which has defined a variable i. In
consequence, i is known in the console as a global variable (that is the
persistence feature)
Now we delete the line therein i = 42 and run script3.py again. At this
point, it will not fail because the console has an object i defined, despite
this was not defined in the program!
Even worse, script1.py does not fail either because there is cross persistence
To prevent this, you can:
Execute in a dedicated console under Run Configure. Every
time we run the code in the Editor, the IPython console in which the
code runs is restarted
Use magic function %reset and keep Execute in current console
Pablo A Macri 28
Spider’s variable explorer
Right-clicking on objects in the Variable Explorer displays
options to plot and analyze these further
Double-clicking on simple variables allows them to be edited
directly, and double-clicking on objects opens a new window
that displays their contents and often allows them to be edited
Python collections (lists, dictionaries, tuples...), Numpy arrays,
Pandas Index, Series and DataFrame, Pillow images and more
can each be displayed and edited in specialized GUI viewers,
and most arbitrary Python objects can be viewed, browsed and
edited

Pablo A Macri 29
jupyter Notebooks
Launch jupyter from the ANACONDA Navigator

Jupyter is just a very reloaded


version of the previous IPython

Pablo A Macri 30
jupyter Menus
File Save and Checkpoint/Revert to Checkpoint
Edit Delete/Split/Merge Cells
The View menu is useful for toggling the visibility of the header
and toolbar. You can also toggle Line Numbers within cells on or
off
The Insert menu is just for inserting cells above or below the
currently selected cell.
The Cell menu allows you to run one cell, a group of cells, or all
the cells. The other handy feature in this menu is the ability to
clear a cell’s output
The Kernel menu is for working with the kernel that is running in
the background. Here you can restart the kernel, reconnect to it,
shut it down, or even change which kernel your Notebook is
using.
Pablo A Macri 31
Adding rich content to jupyter
There are 2 working modes: command (for interacting with
cells) and edit (to enter code). You can switch between them
with <esc> and <shift+enter> . For executing a cell just press
<shift+enter> in edit mode
There are technically four cell types: Code, Markdown, Raw
NBConvert, and Heading.
The Heading cell type which is no longer supported.
The Raw NBConvert cell type is only intended for the
NBConvert command line tool. It allows you to control the
formatting when converting from a Notebook to another
format.
The primary cell types that you will use are the Code and
Markdown cell types. Let’s start learning how to style your
text with Markdown.
Pablo A Macri 32
Styling Your Text in jupyter
Jupyter Notebook supports Markdown, which is a markup
language that is a superset of HTML.
Set a new cell to Markdown and then add the following text to
the cell:

When you run the cell, the output should look like this:

Pablo A Macri 33
Styling Your Text in Jupyter, cont’
You can create headers in Markdown using the pound sign. The more pound
signs you use, the smaller the header. Jupyter Notebook even kind of previews it
for you

Watch out!
This is not a
Python
comment #.
It is a header
in Markdown
Language!

When you run the cell (shift + enter), the output should look like this:

Pablo A Macri 34
Styling Your Text in jupyter, cont’
You can create a list (bullet points) by using dashes, plus signs,
or asterisks.

Pablo A Macri 35
Styling Your Text in jupyter, cont’
If you want to insert a code example that you don’t want your
end user to actually run, you can use Markdown to insert it. For
inline code highlighting, just surround the code with backticks.
If you want to insert a block of code, you can use triple
backticks and also specify the programming language.

Pablo A Macri 36
jupyter Notebooks Final Remarks
Most of the times, the flow in your notebook will be top-to-
bottom, but it’s common to go back to make changes. In this case,
the order of execution is stated to the left of each cell, as In [2],
will let you know whether any of your cells have stale output. And if
you ever wish to reset things, there are several useful options from
the Kernel menu:
Restart: restarts the kernel, thus clearing all the variables that were defined
Restart & Clear Output: same as above but will also wipe the output
displayed below your code cells.
Restart & Run All: same as above but will also run all your cells in order from
first to last.
Interrupt: If your kernel is ever stuck on computation and you wish to stop it,
you can choose the Interrupt option.
For more, see https://medium.com/velotio-perspectives/the-ultimate-beginners-
guide-to-jupyter-notebooks-6b00846ed2af

Pablo A Macri 37
JupyterLab – a reloaded jupyter

Pablo A Macri 38
JupyterLab – a reloaded jupyter

https://towardsdatascience.com/jupyter-lab-evolution-of-the-jupyter-notebook-5297cacde6b

Pablo A Macri 39
Pablo A Macri 40
Python: First Steps
Basic data types
Variables
Operators and Expressions
Built-in functions

Pablo A Macri 41
Python Programs
A program is a sequence of definitions and
commands
definitions are evaluated
commands are executed by Python interpreter in a
shell
commands (statements) instruct interpreter to
do something
can be typed directly in a shell or stored in a
file that is read into the shell and evaluated

Pablo A Macri 42
Objects
programs manipulate data objects
objects have a type that defines the kinds of
things programs can do to them
objects are
scalar (cannot be subdivided)
non-scalar (have internal structure that can be
accessed)

Pablo A Macri 43
Basic Scalar Objects
int – represent integers, ex. 5
float – represent real numbers, ex. 7.31
bool – represent Boolean values True and False
NoneType – special and has one value, None
can use type() to see the type of an object

Pablo A Macri 44
More on Integers
Python interprets a sequence of decimal digits without any
prefix to be a decimal number

The following strings can be prepended to an integer value to


indicate a base other than 10

Pablo A Macri 45
More on Floats
Almost all platforms represent Python float values as 64-bit
“double-precision” values, according to the IEEE 754 standard.
In that case, the maximum value a floating-point number can
have is approximately 1.8 ⨉ 10308. Python will indicate a
number greater than that by the string inf

The closest a nonzero number can be to zero is approximately


5.0 ⨉ 10-324. Anything closer to zero than that is effectively zero

All this is related with numerical errors we are going to discuss later

Pablo A Macri 46
Complex Numbers
Complex numbers are specified as
<real part> + <imaginary part> j

Pablo A Macri 47
Type Conversions (cast)

can convert object of one type to another


float(3) converts integer 3 to float 3.0
int(3.9) truncates float 3.9 to integer 3

Pablo A Macri 48
Built-in Functions
The Python interpreter supports many functions that are built-
in: sixty-eight, as of Python 3.6

https://docs.python.org/3/library/functions.html
Pablo A Macri 49
Built-in Functions

Pablo A Macri 50
Printing
To show output from code to a user, use
print() command

No Out[4] because no value


returned, just something printed.

Pablo A Macri 51
Binding variables and values
equal sign is an assignment of a value to a
variable name
variable value
pi = 3.14159

pi_approx = 22/7

value stored in computer memory


an assignment binds name to value
retrieve value associated with name or variable
by invoking the name, by typing pi
Pablo A Macri 52
Abstracting Expressions
why give names to values of expressions?
reuse names instead of values
easier to change code later
These = are assignments
• value on the right
pi = 3.14159 • name on the left

radius = 2.3
area = pi*(radius**2)
radius = 2.7
area = pi*(radius**2)
Pablo A Macri 53
Programming vs Maths
We are no talking about equations here
pi = 3.14159
radius = 2.2
# area of circle
area = pi*(radius**2)
radius = radius+1 This is an assignment equivalent to
radius += 1
area= pi*(radius**2)

Pablo A Macri 54
Changing Bindings
can re-bind variable names using new
assignment statements
previous value may still stored in memory but
lost the handle for it
pi = 3.14159
radius = 2.2
area = pi*(radius**2)
radius = radius+1

This is because float and int are immutable objects, they don’t change in-place. More on this later.

Pablo A Macri 55
Changing Bindings
can re-bind variable names using new
assignment statements
previous value may still stored in memory but
lost the handle for it
pi = 3.14159
radius = 2.2
area = pi*(radius**2)
radius = radius+1

This is because float and int are immutable objects, they don’t change in-place. More on this later.

Pablo A Macri 55
More on Variables
Dynamical typing: a variable may be assigned a value of one
type and then later re-assigned a value of a different type

Object References: every item of data in a Python program is


an object of a specific type or class
Here the interpreter does the following:
• Creates an integer object
• Gives it the value 300
• Displays it to the console

Pablo A Macri 56
More on Variables, Object Reference
A Python variable is a symbolic
name that is a reference or
pointer to an object.
Once an object is assigned to a
variable, you can refer to the
object by that name. But the data
itself is still contained within the
object.

Pablo A Macri 57
More on Variables, Object Identity
The built-in Python function id()
returns an object’s integer identifier. Using
the id() function, you can verify that two
variables indeed point to the same object

Watch this. Here, m and n are separately


assigned to integer objects having value
30. But in this case, id(m) and id(n)
are identical! For purposes of optimization,
the interpreter creates objects for the
integers in the range [-5, 256] at
startup, and then reuses them during
program execution.
Pablo A Macri 58
Variable Names
Officially, variable names in Python can be any length and can
consist of uppercase and lowercase letters (A-Z, a-z), digits (0-
9), and the underscore character (_). An additional restriction is
that, although a variable name can contain digits, the first
character of a variable name cannot be a digit.

Variable names are case sensitive!

Pablo A Macri 59
Variable Name Style
suppose you are counting the number of people who have
graduated college.

all of them are probably better choices than n, or ncg, or the


like. At least you can tell from the name what the value of the
variable is supposed to represent.

Pablo A Macri 60
Variable Name Style
The most commonly used methods of constructing a multi-
word variable name are
Camel Case: Second and subsequent words are capitalized, to make
word boundaries easier to see
• Example: numberOfCollegeGraduates
Pascal Case: Identical to Camel Case, except the first word is also
capitalized
• Example: NumberOfCollegeGraduates
Snake Case: Words are separated by underscores
• Example: number_of_college_graduates

The Style Guide for Python Code, also known as PEP 8, contains
Naming Conventions that list suggested standards for names of
different object types. PEP 8 includes the following
recommendations: https://peps.python.org/pep-0008/
Snake Case should be used for functions and variable names.
Pascal Case should be used for class names.
Pablo A Macri 61
Reserved Words (Keywords)
No object can have the same name as a reserved word. In
Python 3.6, there are 33 reserved keywords:

Pablo A Macri 62
Expressions
combine objects and operators to form
expressions
an expression has a value, which has a type
syntax for a simple expression
<object> <operator> <object>

Pablo A Macri 63
Operators on ints and floats
i+j sum
• If boht are int, result is int
i-j difference • If either or both are floats,
result is float
i*j product
i/j division result is float

i//j int division result is int, quotient without


remainder
i%j the remainder when i divided by j
i**j i to the power j

Pablo A Macri 64
Operator Precedence
parentheses used to tell
Python to do these operations
first
3*5+1 evaluates to 16
3*(5+1)evaluates to 18
operator precedence without
parentheses

8 ÷ 2*(2+2) = ?
See pemdas vs bodmas controversy
in NYT

Pablo A Macri 65
Comparison Operators
i and j are any variable names (int or float)
i>j
i>=j
i<j
i<=j
i==j equality test, True if i equals j
i!=j inequality test, True if i is not equal to j

Pablo A Macri 66
Equality Comparison on Floats
The value stored internally for a float object may not be
precisely what you’d think it would be!!
Important issue regarding
numerical errors

The preferred way to determine if two floating-point values are


“equal” is to compute whether they are close to one another,
given some tolerance

abs() returns absolute value

Pablo A Macri 67
Logic Operators on Bools
a and b are any bool type variable names
not a True if a is False; False if a is True

a and b True if both are True


a or b True if either or both are True

Identity Operator on objects


a is b True if id(a)==id(b) is True
id(a) gives the memory position of object a

Pablo A Macri 68
Evaluation of Non-Boolean Values in Boolean Context
All the following are considered false when evaluated in
Boolean context:
The Boolean value False
Any value that is numerically zero (0, 0.0, 0.0+0.0j)
An empty string
An object of a built-in composite data type which is empty
The special value denoted by the Python keyword None

Pablo A Macri 69
Python
An ultra-crash course

Pablo A Macri 70
Conditionals
Conditionals
Grouping statements: indentation and blocks
The else and elif clauses

Pablo A Macri 71
Branching Programs
The simplest branching statement
is a conditional
A test (expression that evaluates to
True or False)
A block of code to execute if the
test is True
An optional block of code to
execute if the test is False

Pablo A Macri 72
The Simplest Conditional

In the form shown above:


<expr> is an expression
evaluated in Boolean
context
<statement> is a valid
Python statement, which
must be indented
See examples to the right

Pablo A Macri 73
Compound if Statement
Now we can see why indentation is so
important in a Python program structure

Pablo A Macri 74
Nested Conditionals
Blocks can be nested to arbitrary depth. Each indent
defines a new block, and each outdent ends the
preceding block.

Pablo A Macri 75
The else Clause
Sometimes, you want to evaluate a condition and
take one path if it is true but specify an alternative
path if it is not. This is accomplished with an else
clause.
If <expr> is true, the first suite is executed, and
the second is skipped. If <expr> is false, the first
suite is skipped and the second is executed.

Pablo A Macri 76
The elif Clause
There is also syntax for branching execution based on several
alternatives. For this, use one or more elif (short for else if)
clauses. Python evaluates each <expr> in turn and executes
the suite corresponding to the first that is true. If none of the
expressions are true, and an else clause is specified, then its
suite is executed

Pablo A Macri 77
More Nested Conditionals

Pablo A Macri 78
Compound bool Expressions

Pablo A Macri 79
One-Line if Statements
It is permissible to write an entire if statement on one line

There can even be more than one <statement> on the same


line, separated by semicolons

There are two possible interpretations:


If <expr> is true, execute <statement_1>. Then, execute
<statement_2> ... <statement_n> unconditionally, irrespective
of whether <expr> is true or not.
If <expr> is true, execute all of <statement_1> ...
Python choice
<statement_n>. Otherwise, don’t execute any of them.

Pablo A Macri 80
One-Line if, elif, and else
Multiple statements may be specified on the same line as an
elif or else clause as well

While all of this works, and the interpreter allows it, it is generally
discouraged on the grounds that it leads to poor readability,
particularly for complex if statements. PEP 8 specifically
recommends against it. https://www.python.org/dev/peps/pep-0008/
Pablo A Macri 81
Conditional Expressions
In its simplest form, the syntax of the conditional expression is
as follows

This is not a control structure that directs the flow of program


execution. It acts more like an operator that defines an
expression. In the above example, <conditional_expr> is
evaluated first. If it is true, the expression evaluates to
<expr1>. If it is false, the expression evaluates to <expr2>.

some users find it particularly


readable for variable assignment

Pablo A Macri 82
The pass Statement
Occasionally, you may find that you want to write what is called
a code stub: a placeholder for where you will eventually put a
block of code that you haven’t implemented yet.

When running foo.py you just will get:

Pablo A Macri 83
Control Flow – Branching recap

<condition> has a value True or False


Evaluates expressions in that block if <condition> is
True
Pablo A Macri 84
All branching types in one slide
simple if else clause

elif clause
nested conditionals

Pablo A Macri 85
What did we learn?
Branching programs allow us to make choices
and do different things
But still the case that at most, each statement
gets executed once.
So maximum time to run the program depends
only on the length of the program
These programs run in constant time

Pablo A Macri 86

You might also like