0% found this document useful (0 votes)
16 views160 pages

Python Programming Basics for Finance

This document is a basic level programming guide for Python, specifically applied to finance, authored by Yessenia Portal Machuca. It covers various topics including Python's characteristics, installation of Anaconda, data types, functions, control statements, and libraries such as Numpy and Pandas. The guide aims to provide foundational knowledge for using Python in financial applications, with practical examples and explanations throughout.

Translated by

ScribdTranslations
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)
16 views160 pages

Python Programming Basics for Finance

This document is a basic level programming guide for Python, specifically applied to finance, authored by Yessenia Portal Machuca. It covers various topics including Python's characteristics, installation of Anaconda, data types, functions, control statements, and libraries such as Numpy and Pandas. The guide aims to provide foundational knowledge for using Python in financial applications, with practical examples and explanations throughout.

Translated by

ScribdTranslations
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

CENTRAL RESERVE BANK

FROM PERU

Programming with Python


Basic Level
Applied to Finance

Yessenia Portal Machuca


yportal@[Link]

January, 2020
PROGRAMMING IN PYTHON
Basic Level

Index
About of Python 6
1.1. What Is it Python? . . . . . . . . . . . . . . . . . . . .6. . . . . . . . .
1.2. Characteristics from Python . . . . . . . . . . . . . . . . . 6. . . . . . . .
1.3. Brief history of Python. . . . . . . . . . . . . . . . . .7. . . . . . . .

2. About of Anaconda and the IDEs for Python 9


2.1. How install Anaconda?. . . . . . . . . . . . . . . . . 9. . . . . . . .
2.2. Starting in Python 13
2.3. Command Navigation in Python22
2.4. Pyflakes ............................ 23

Identifiers of Python 24
3.1. Rules to write identifiers24
3.2. Some considerations. . . . . . . . . . . . . . . . . . . . . . . . . . 24

4. Operators 25
4.1. What Who are the operators? 25
4.2. Operadores arithmetic25
4.3. Operators of comparison (relational)26
4.4. Operators logical (boolean) 27
4.5. Operators of Assignment 27
4.6. Operators Specials...
4.6.1. Operator of identity . . . . . . . . . . . . . . . . . . . . . . . 28
4.6.2. Operator of Membership 28

5. Types of Data 30
5.1. Indexing30
5.2. Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
5.3. Sequences32
5.3.1. Chains Strings...
5.3.2. List35
5.3.3. Tuple 39
5.4. Sets (Set) 40
5.5. Dictionary 41
5.6. Conversion between data types 42

6. Entrance and Exit 43


6.1. Function Input43
6.2. Entry of files: import 43
6.3. Output using the functionprint()44
6.4. Output of files: export 46

7. Sentence, indented and comments 47


7.1. Sentence 47
7.1.1. Declaration multiline47
7.2. Indentation 47
7.3. Comments from Python 48

Yessenia Portal Machuca 2 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

7.3.1. Comments multiline49


7.3.2. Docstring 49

8. Sentences of Control 50
8.1. Sentences selective: If, If-Else and If-Elif-Else 50
8.1.1. Sentence Selective if 50
8.1.2. Sentence Selective if...else 50
8.1.3. Sentence if...elif...else51
8.1.4. Sentences if nested 51
8.1.5. Operator ternary . . . . . . . . . . . . . . . . . . . . . . . . . . 52
8.2. Sentences iterative52
8.2.1. Judgment Iterative for 53
8.2.2. Sentence While loop. . . . . . . . . . . . . . . . . . . . . . 54

9. Functions 56
9.1. What Is it a function in Python? 56
9.2. Types of functions56
9.2.1. Function conventional56
9.2.2. How call a function? . . . . . . . . . . . . . . . . . . . 57
9.2.3. The return statement 57
9.2.4. Types of function arguments 58
9.2.5. Functions Lambda60
9.3. Docstring 60
9.4. Scope and lifespan of the variables61
9.5. Storage of its functions in Modules 62

10. Classes and objects 63


10.0.1. What is an Object? 63
10.0.2. What is a Class? 63

[Link] 65
11.1. What are packages? . . . . . . . . . . . . . . . . . . . . . . . . . . 65
11.2. The Scientific Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
11.3. What are modules in Python?. . . . . . . . . . . . . . . . . . . . . 67
11.4. How to import modules in Python? ............... 67
11.5. Import judgment68
11.6. Import with renaming68
11.7. Judgment from ... import ... . . . . . . . . . . . . . . . . . . . . . . . . 69
11.8. Import all functions69
11.9. Python module search 70
[Link] a module70
[Link] internal functiondir()71

12. Numpy Library 73


12.1. What is Numpy?...
12.2. How can I create an array? 73
12.3. Combine arrays and data types in NumPy76
12.4. Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
12.5. Broadcasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

Yessenia Portal Machuca 3 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

12.6. Aggregate functions 79


12.7. Indexing .................................................. 80
12.7.1. Basic slicing. .................. 80
12.7.2. Advanced Indexing. 81
12.8. Structured sets 82

13. Pandas 84
13.1. What is Pandas?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
13.2. Series84
13.2.1. Creation and indexing of Series 85
13.2.2. Size, shape, and value count 88
13.2.3. Alignment using index labels89
13.3. The DataFrame 90
13.3.1. Creation of a DataFrame 90
13.3.2. Selection of columns from a DataFrame 93
13.3.3. Selection of rows from aDataFramethrough the index ...
13.3.4. Selection of lines using Boolean selection. . . . . . . . . 97
13.3.5. Arithmetic in a DataFrame 98
13.4. Reindexing of objectsSeriesyDataFrame99
13.5. DataFrame Manipulation Applied to Finance.103
13.5.1. Data reorganization and restructuring 104
13.5.2. Grouping and aggregation115

[Link] 122
14.1. Introduction ...
14.2. Pyplot 123
14.3. Multiple figures 124
14.4. Elements of the graphic . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
14.4.1. Text126
14.4.2. Grid 129
14.4.3. Legend 130
14.5. Types of graphs132
14.5.1. Line graphs 132
14.5.2. Line graphs with pandas 134
14.5.3. Histograms 135
14.5.4. Bar charts . . . . . . . . . . . . . . . . . . . . . . . . . 136
14.5.5. Horizontal bar charts 138
14.5.6. Multiseries bar graphs with pandas DataFrame ... 140
14.5.7. Stacked multi-series bar charts ...
14.5.8. Stacked bar graphs with a pandas DataFrame. . . . . 142
14.5.9. Other Representations of Bar Graphs143
[Link] charts144
[Link] charts with a pandas DataFrame ....... 147
[Link] graphics: Polars 147
14.6. 3D Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
14.6.1. 3D Surface 149
14.6.2. 3D bar charts150
14.7. Multi-Panel Graphics 151
14.7.1. Visualize subplots within other subplots151

Yessenia Portal Machuca 4 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

14.7.2. Subplot Grids . . . . . . . . . . . . . . . . . . . . . . 152

15. Packages for financial applications 153


15.1. Statsmodels 153
15.2. Visualize Wealth 159

Yessenia Portal Machuca 5 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

1. About Python
1.1. What is Python?
Python is a programming language-
multiplatform action (that is, it acts-
cuts on multiple platforms such as
Windows, Mac OS X, Linux, Unix and
it has even adapted to the machi-
Java and .NET virtual machines.

Python is available for everyone


main operating systems, such as
Windows, Linux / Unix, OS / 2 and
Mac. It is an easy language to learn.
of understanding, the majority of the free-
rías/modules and tools available
bless you are open source and general-
minds come with free licenses.
The continuous improvement of the Pyt language
it has been possible thanks to a gr
for dedicated people and buy-
inserted to support the cause of propor-
to cut the service.

1.2. Characteristics of Python


The following describes the most important features of Python:

1. Easy: The code, in Python, is concise and effective and therefore understandable.
manageable.

2. Write and Execute: In Python, a code can be easily executed by creating


and executing scripts. Python also provides the user with an interactive environment.
in which independent commands can be executed.

[Link]: The syntax of Python is simple, this makes learning and


understanding of the process is easy. According to most authors, the three
The main features that make Python attractive are: it is simple, small,
flexible.
[Link]: Python allows the integration of other programming languages, with the
Scipy module.

[Link] writing: Python has its own way of managing memory


associated with the objects. When an object is created in Python, memory is allocated to it.
assigns dynamically. When the object's life cycle ends, the memory is
recovers from it. This memory management of Python makes programs be
more efficient.

Yessenia Portal Machuca 6 yportal@[Link]


PROGRAMMING IN PYTHON
Nivel Básico

6. Type of objects generated: Python has built object types. This makes
that the task to be done is easy and manageable.

Numerous libraries and tools: The task to be performed becomes easy, given
due to the fact that most common tasks (in fact, not so common ones too)
they have already been programmed in Python.

[Link]: A program written in Python can run on almost all


known platforms, whether Windows, Linux or Mac.
[Link]: Python is not proprietary software, it is possible to download from various
available options. In addition, there are no known legal issues related to
the distribution of Python.

1.3. Brief history of Python


The history of the Python programming language1 dates back to the late 80s
and the beginning of the 90s, its implementation started in December 1989 when in
Christmas, Guido Van Rossum2 who worked at CWI (a research center ho-
official language that) decided to start the project as a hobby giving it
continuation of the programming language ABC of which I had been part of the team of
development in CWI, this language focused on being easy to use and learn.
having power in its performance but the hardware available at the time of its creation.
made its use difficult and the project did not transcend as expected. Van Rossum is by
both the main author of Python and3 continues to play a central role, deciding
the direction of language; in the Python community, it is known as Benevolent
Lifelong Dictator.
Python has applications in:

Development of graphical user interface (GUI)

Web pages

Database programming

Gambling

Component-based programming

The scientific analysis

Machine Learning, among others.


1 The
name of the language comes from the BBC show 'Monty Python's Flying Circus' (the circus
Monty Python's ambulatory) and has nothing to do with unpleasant reptiles.
2 Guido van Rossum is a computer scientist at the University of Amsterdam. In the year

In 2001, he received the FSF Award for the Advancement of Free Software for having invented and implemented
the Python programming language. In December 2005, he was hired as a developer by the
American company Google, and after seven years, at the beginning of December 2019, announces its
withdrawal from the American company to join Dropbox in January 2013.
3 Thecontinuous central role of Guido van Rossum in the leadership of Python is reflected in the title.
that the Python community gave him, "Benevolent Dictator For Life" (BDFL, for its initials in Spanish)
English).

Yessenia Portal Machuca 7 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Figure 1: Some applications of Python

Python
applications

Web GUI Software Scientific


Finance
development development development applications

Numpy, Pandas
Django Kiwi Scions Scipy, Matplotlib [Link]
statsmodels pandas_datareader
yahoo-finance
Python finance
finance,economics.

Many development environments and editors are available for Python. Some
the following are from them:

Spyder

2. Jupyter Notebook

3. Jupyter Lab

4. PyDev with Eclipse

5. Emacs

6. Vim

7. Gedit

8. Idle

9. PIDA (Linux)(VIM based)

10. BlueFish (Linux)

Yessenia Portal Machuca 8 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

2. About Anaconda and IDEs for Python


Anaconda Navigator is a free distribution graphical user interface (GUI)
of the Python and R languages, which allows for easy application startup and management
packages, environments, and channels without using commands. Navigator can search for packages in
Anaconda Cloud or in a local Anaconda repository. It is aimed at simplifying the
deployment and management of packages, and is available for Windows, macOS and
Linux.

2.1. How to install Anaconda?


To install Anaconda you must follow these steps:

Step 1: go to[Link]

Yessenia Portal Machuca 9 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Step 2: Run the downloaded .exe file to begin the installation.

Click on: 'I Agree'.

Yessenia Portal Machuca 10 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

-Select 'Just Me' if you only want it to be installed for your Windows user.

Choose the folder where the program will be installed.

Yessenia Portal Machuca 11 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Click on 'Install'.

Click on Next.

Yessenia Portal Machuca 12 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Click on 'Finish'.

2.2. Getting Started with Python

There are several ways to start Python: 1) in immediate mode, or 2) From a


IDE. This course explores IDEs: JupyterLab, Jupyter Notebook, and Spyder.

Yessenia Portal Machuca 13 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Immediate mode

Python 3.7.4 (latest version as of the date) you can download it from the link:
[Link]

We can write Python expressions directly and press enter to


obtain the output.
>>>
it is the Python prompt, which indicates that the interpreter is ready to start.
To exit this type of mode, you must type exit() or quit() and press
enter.
This prompt can be used as a calculator. In Python it can be
add, subtract, multiply, divide and execute in the command line.
∗ Multiplication can be done using the file *
∗ Division can be performed using the operator /
∗ Exponentiation can be done using the ** operator
∗ The module can be found using the command %. The operator of the
module finds the remainder if the first number is greater than the other,
the opposite returns the first number as output.

Yessenia Portal Machuca 14 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

The results of the operations are shown below:

2. In an Integrated Development Environment (IDE)

The use of an IDE can eliminate redundant tasks and significantly reduce
the time required for application development.
The IDE is a piece of software that provides useful functions such as its-
code management, syntax highlighting and checking, explorers of
files, etc. to facilitate the programmer's development of applications.
An IDE is used to run a Python program written in a file.
That file is called unscript.
Losscripts can be saved to disk for future use. It is important.
It should be mentioned that to write a Python script file, one can use any.
which text editing software. It should only be saved with the extension
.py.
The following are three IDEs (free) that will be explored in the course:

a) Spyder Script Mode

∗ Spyder is a development environment


multi-integrated roll
open source platform
for scientific programming in
the Python language, which is pu-
published under the MIT license. Ini-
specially created and developed
by Pierre Raybaut in 2009.
It is available multiplatform
but through Anaconda, in
Windows, on macOS through
from MacPorts and in the main
Linux distributions.

Yessenia Portal Machuca 15 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

∗ The default window of Spyder has three panels: the panel of


IPython, the editing panel and the help panel.

∗ The IPython panel (IPython Pane) is the main way that in-
You interact with Python. It can be used to run programs of
Python computer, test Python code snippets, navigate through
the computer's file directories and perform system tasks
how to create, move, and delete files and directories. The prompt of
the default input of the IPython panel looks like this:
In [1]:
This notice means that Spyder is running the IPython shell.
∗ The Editor Pane allows you to write and edit programs
more Python (or scripts), which are simply sequences of commands
two Python (code) stored in a file on your computer.
∗ The Help Pane in Spyder provides assistance with the commands.
two of Python. An interesting feature of the Spyder IDE is
that if you place the cursor next to or inside the name of a function
and press Ctrl+I, the web documentation of the function is displayed
in the Help Panel. Another way to obtain information from a
function, is executing the help command, followed by the name of the
function in parentheses, for example:
In [1]:help(range)

∗ These panels in the Spyder window are reconfigurable and des-


mountable, it is possible to adjust the total size of the window to
that fits your computer screen. You can find more
information about Spyder in[Link]

Important: Python distinguishes between uppercase and lowercase.


Therefore, two words spelled the same way but
different uppercase letters are treated as names
different in Python.

Yessenia Portal Machuca 16 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

∗ In the following figure, an example of execution in mode is visualized.


scripts ([Link]) and execution from the interpreter.

Script mode execution

Execution from the


interpreter

∗ To create a script file follow these steps:


Step 1. Go to New file (Ctrl+N)
Step 2. Save the file as [Link]
Step 3. Write the Python code in the file
print(2+3)
print(2*3)
print(2**3)
print(2/3)
print(2 % 3)
print(3/2)

Step 4. Click the run button in the Spyder IDE. It will be visualized.
he curses the following output.

Yessenia Portal Machuca 17 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

b) Jupyter Notebook mode

Allows interactive work


go, store and execute programs
in a Jupyter notebook just like
it would be done within the Spyder IDE. A
Jupyter notebook, it's excellent for-
to record a job in Python,
and very useful in a work environment
story to read, record, and analyze
data, deliver tasks, document
and test the software.

To start in Jupyter Notebook, run the software in the panel.


Anaconda and this will start the Jupyter web application, showing
Jupyter Notebook Dashboard as a page in your web browser pre-
finished.

In the lower left corner of the control panel, there is a list of folders
(and files) from the default directory. You can navigate to the folder
Where do you want to save your work, or create a new folder, by doing
click on the New button located at the top right of the panel and
selecting Folder. Finally, to create a new Jupyter notebook
Go to the New dropdown menu on the right side of the page and
select Python 3.

When a new Jupyter notebook is opened, an interactive IPython is apa-


rece con el mensaje:
In[ ]:
In this cell, you can write the code as you would in the IPython panel.
from the IDE Spyder. For example, writing in the cell
5+5
and to execute press Shift+Enter.

Yessenia Portal Machuca 18 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Jupyter Notebook

∗ Jupyter notebooks are web applications that run locally.


mind and that contain Python code, LaTeX code and Mark text-
down. The standard language is Python, however, please note
that a variety of alternatives are compatible, such as
R.
∗ A Jupyter notebook will be easier to understand if it includes annotations.
Don't explain what you are executing in the notebook. Besides
register the entries and exits of the calculations, the Jupyter notebooks
allow the user to insert headers, explanatory notes, express-
mathematical sessions and images.

∗ Headers and text: Let's suppose, for example, that we want


to have a title at the top of the Jupyter dialog window
with which we have been working, and we want to include the name
from the session's author. To do this, we scroll the Jupyter to
the top and place the cursor in the first cell, we insert
a new cell and we select Markdown cell type, inmedia-
completely disappears the indicator
In [ ]:
indicating that this box is NO longer for executing Python code.
Next, write# enter text. Remember that each#
it additionally decreases the font size.

∗ Mathematical expressions: It is also possible to include expressions


mathematics, in a cell of a Jupyter notebook. Likewise
The type of Markdown cell should be chosen and the expression typed.
mathematics using LaTeX language (you can obtain information
in this regard[Link]
\begin{align}
x = \int_0^T v(t)\, dt
\end{align}

Yessenia Portal Machuca 19 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

∗ Insert images: to include images in your Jupyter notebook,


like JPEG and PNG, use the image class from the display module
from the IPython package. For example, by running the following code
show the following output.
from [Link] import Image
Image(url=’[Link]

∗ Inserting YouTube videos: the module [Link] of pa-


The IPython package contains a YouTubeVideo function, where you can
insert externally hosted videos on YouTube. For example, axis-
cute the following code:
from [Link] import YouTubeVideo

Video on how to install Anaconda.


YouTubeVideo(’52h3r_lROGY’)

The video will be displayed below the code, as shown in the figure.
previous

Yessenia Portal Machuca 20 yportal@[Link]


PROGRAMACIÓN EN PYTHON
Basic Level

∗ Edit and rerun a Jupyter notebook: When working with


a Jupyter notebook, you may want to move some cells, or
delete some cells, or simply change some of them.
All these tasks can be done from the edit menu, as long as
that to run the code of a notebook again you can do it
from the kernel menu by selecting 'Run All'.
Exit a Jupyter notebook: When you are ready to stop
working with a Jupyter notebook, click on the close item
and stop from the File menu. The browser tab will close.
and return to the Jupyter dashboard. Finally, close the pes-
Open the IPython Notebook Dashboard in your browser to finalize.
the session.
–Work with an existing Jupyter notebook: Start the Dash-
Jupyter board where I should see a list of all the notebooks
In our Jupyter in that directory. Click on the name of the notebook.
what you want to open. To initialize all the objects from the file, you must
run the file again.

c) JupyterLab mode
JupyterLab is a web-based interactive development environment for
code and data Jupyter. While JupyterLab allows the use of notebooks
Jupyter goes beyond the classic Jupyter Notebook by providing a
flexible and extensible web application with a set of components
reusable.
∗ JupyterLab is flexible: the interface must be configured and organized
user to support a wide range of workflows in science
data, scientific computing, and Matching Learning.
∗ JupyterLab is extensible and modular: write plugins that add new
your components and integrate with the existing ones.

Bloomberg has recently incorporated the BQuant platform.


using Jupyter notebooks, allowing for the writing of code
Python that makes use of Python libraries and the finance library
Bloomberg Terminal (PyBQL) with which notebooks can be created
interactive computer scientists to conduct and document the analyses
financial, without leaving the terminal.

Yessenia Portal Machuca 21 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

2.3. Navigation Command in Python


IPython recognizes several common navigation commands that are used under the
Unix/Linux operating systems. The following commands work on Macs, Win-
Windows and Linux.

To set your computer in the default home directory, use the following
code:
In [1]: %cd ~
/Users/Yessenia

To show the current directory path of the computer, you can use the code:
In [2]: %pwd
/Users/Yessenia

To create a folder inside your documents directory, type the code %ls
to list the files and directories in your root directory, then write %mkdir
programs and this new folder will be created in your directory. Finally, to validate
a new folder has been created, run %ls.
In [7]: %cd ~
/Users/pine
In [8]: %ls
Applications/ Library/ Pictures/
Desktop/ Movies/ Public
Documents/ Music
Downloads/ News/

In [9]: %mkdir programs

In [10]: %ls
Applications/ Library/ Pictures/
Desktop/ Movies/ Public/
Documents/ Music programs/
Downloads/ News/

To configure your directory to a specific path, run the following code:


imports
[Link]('C:\Users\Yessenia\Downloads')

To clear the IPython terminal, type the command %clear or cls, which will give you
a new interpreter window.

Yessenia Portal Machuca 22 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

2.4. Pyflakes
One way to avoid errors is to use a syntax checker. Fortunately,
The Spyder IDE includes a syntax checker called Pyflakes that
executes in the background when editing a Python program using
Spyder. If there is an error in your code, Pyflakes marks the error.

The Spyder Editor provides syntax highlighting, which encodes keywords, co-
comments and other features of Python syntax according to its function, and
therefore it facilitates code reading and the detection of programming errors.
The spell checker also provides syntax checking, such as a
spell checker in a word processing program that identifies
many coding errors. This can greatly speed up the process of
coding.

In Spyder, a red circle appears to the left of the line where Pyflakes thinks
that the error occurs. A yellow triangle appears to the left of the line where
Pyflakes thinks that the coding style does not conform to PEP 8 standards.4 this
It is not an error, just a violation of coding style, which you can ignore.
or to take into account. When hovering the mouse pointer over the red or yellow icon,
a code analysis box appears with a brief message describing the error
or the style infringement.

4 It
is a style guide document for Python, which is not mandatory to follow, but is highly recommended.
recommended. You can find more information at:[Link]

Yessenia Portal Machuca 23 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

3. Python Identifiers
An identifier is the name assigned to entities such as classes, functions, variables,
etc; helping to differentiate one entity from another.

3.1. Rules for writing identifiers


1. Identifiers can be a combination of lowercase letters (from aaa
it can be in lowercase (from a to z), in uppercase (from A to Z), in digits (from 0 to 9), or an underscore

(_).
Names like 'miClase', 'var_1', 'yy' print on screen, are valid examples.
two.
2. An identifier cannot start with a digit. 1variableno is not valid, but
variable1 is perfectly fine.

3. Keywords cannot be used as identifiers.


>>>global= 1
File "<interactive input>", line 1
global= 1
^
SyntaxError: invalid syntax

4. We cannot use special symbols like !, @, #, $, %, etc. in our identifier.


frame.
a@ = 0
File "<interactive input>", line 1
a@ = 0
^
SyntaxError: invalid syntax

5. The identifier can be of any length.

3.2. Some considerations


Let's remember that Python is a case-sensitive language (distinguishes between uppercase and lowercase).
uppercase and lowercase letters); that is, Variable and variable are not the same.

It is always advisable to name identifiers that make sense;


For example, count=10 is valid, but writing counter=10 would make more sense and would be
easier if it were to create a variable that is responsible for carrying out an operation
of counting.
Multiple words can be written separately:

∗ using a hyphen, this_is_a_long_variable, or


∗ using camel case style, that is, capitalizing each first...
the letter of the word, except for the first one, and without separating them; for example:
camelCaseExample

Yessenia Portal Machuca 24 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

4. Operators
4.1. What are operators?
Operators are special symbols in Python that perform arithmetic calculations.
or logicals.
The value at which the operator operates is called operand.

For example:
>>> 2+3
5

Here, + is the operator that performs the addition, 2 and 3 are the operands and 5 is the output.
of the operation.

4.2. Arithmetic operators


Arithmetic operators are used to perform mathematical operations such as
addition, subtraction, multiplication, etc.

Operator Meaning Example


Add two operands x+y
+
or a unary +2
Subtract the right operand from the left one x-y
-
or less unary -2
* Multiply two operands x*y
Divide the left operand by the right
/ x/y
(always results in float)
Module - remainder of the division of o x%y
%
waiting left for the right (resto dex/y)
Floor division: division that results in a number
// x divided by y
whole number aligned to the left on the number line
Exponent - left operand x raised to the power of y
**
raised to the power of the right operator (the power)

Example: Arithmetic Operators

∗ The following code is given x * y


x = 15
y = 4 # Output Div:
x / y
Output sum:
x + y # Output Div_p:
x divided by y

# Output dif:
x - y # Output Potencia:
x raised to the power of y

Output mult:

Yessenia Portal Machuca 25 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

∗ After being executed line by line, it Out[9]: 60


obtain the following output x / y
x + y Out[10]: 3.75
19 x // y
x - y 3
Out[8]: 11 x ** y Out[12]: 50625
x * y

4.3. Comparison (relational) operators


Comparison operators are used to compare values. They return True
False according to the condition.

Operator Meaning Example


Greater than
> x is greater than y
True if the left operator is greater than the right
Less than
< x is less than y
True if the right operator is greater than the left
Identical to
== x==y
True if both operands are equal
Different from
!= x is not equal to y
True if both operands are different
Greater than or equal to
>= x >= y
True if the left operator is greater than or equal to the right
Less than or equal to
<= True if the right operator is greater than or equal to the left one
x is less than or equal to y

Example: Comparison Operators


x = 10
y = 12

x > y is False
x is greater than y

x < y is True
x is less than y

x == y is False
x==y

x != y is True
x is not equal to y

x >= y is False
x is greater than or equal to y

x <= y is True
x is less than or equal to y

Yessenia Portal Machuca 26 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

4.4. Logical (Boolean) Operators


Logical operators are the operators and, or, and not.

Operador Significado Example


and True if both are true x*y
or True if at least one of the operands is true x*y
not True if the operator is false (complements the operand) (remainder dex/y)

In many cases, the execution of a block depends on the true value of more than one
sentence. In these cases, the operators "and" ("&") and "or" ("|") are used
in our rescue. The first ('and') is used when the output is 'true',
when both conditions are 'true'. The second ('or') is used if the output
it is 'true' if any of the conditions is 'true'.
Example: Logical Operators
x = True
y = False

x and y is False
xandy

x or y is True
xory

not x is False
notx

4.5. Assignment Operators

Example Operator Equivalent to


= x = 5 x = 5
+= x += 5 x = x + 5
/= x -= 5 x = x - 5
%= x %= 5 x = x % 5
//= x //= 5 x = x//5
**= x **= 5 x = x**5
&= x &= 5 x = x&5
|= x |= 5 x = x|5
^= x XOR 5 x = x^5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x<<5

4.6. Special Operators


The Python language offers a special type of operators such as the operator of
identity or the membership operator.

Yessenia Portal Machuca 27 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

4.6.1. Identity operator


They are not identity operators. They are used to verify if two values
(o variables) are located in the same part of the memory.
Two variables that are equal do not imply that they are identical.

Operator Meaning Example


True if the operands are identical
is xes True
(they refer to the same object)
True if the operands are not identical
is not x is not True
(they do not refer to the same object)

Example: Identity Operators


x1 = 5
y1 = 5
x2 =’Hello’
y2 =’Hello’
x3 = [1,2,3]
y3 = [1,2,3]

# Output: False
x1 is not y1

# Output: True
x2isy2

# Output: False
x3isy3

In the example Identity Operators:

∗ It is visualized that x1yy1 are integer numbers of the same values, for the
they are equal and identical. The same happens with x2yy2 (strings).
∗ However, they are lists. They are the same but not identical. It's because the
interprets them separately in memory even though they are the same.

4.6.2. Membership Operator


membership operators in Python. They are used to test
if a value or variable is found in a sequence (string, list, tuple, set)
and dictionary).

In a dictionary, we can only test for the presence of a key, not the value.

Operator Meaning Example


True if the value/variable
in 5 in x
is found in the sequence
True if the value/variable
is not 5 not in x
not found in the sequence

Yessenia Portal Machuca 28 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Example: Membership Operators


x =’Hello world’
y = {1:’a’,2:’b’}

# Output: True
Hinx

# Output: True
hellonot inx

# Output: True
1iny

# Output: False
'a'tiny

Yessenia Portal Machuca 29 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

5. Data Types
Python allows the user to manipulate variables to store values, and each value
In Python, there is a data type (they do not need to be declared).

Objects in Python have identity, a type, and a value (given by the user)
or a default value). Identity in Python refers to the address and not
change. The data type can be any of the following.

None: This represents the absence of a value.

[Link]: Python has three types of numbers:

a) Integers: It has no fractional part.


b) Float: It can store a number with a fractional part.
c) Complex: It can store real and imaginary parts.
3. Sequences: They are ordered collections of elements. There are three types of sequences.
in Python:

a) Strings
b) Tuples
c) Lists (list)

[Link]: It is a collection of unordered elements.

a) Sets
b) Dictionaries

5.1. Indexing
In Python, the index operator [] allows you to access an element of a
sequence.

The index of the element to be accessed must be an integer.

The syntax of the operator [] is as follows.


<sequence_name>[index]

In Python, the first element is at position 0, not at position 1.

The following graphic illustrates the types of indexing.


>>> +---+---+---+---+
>>> |-4 |-3 |-2 |-1 | <= negative indexes
>>> +---+---+---+---+
>>> | A | B | C | D | <= sequence elements
>>> +---+---+---+---+
>>> | 0 | 1 | 2 | 3 | <= positive indexes
>>> +---+---+---+---+

Yessenia Portal Machuca 30 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Each object stored in a sequence has an associated index number.


site, zero indexed and starting from the left, and the negative that starts
-1 from the right.

In Python, the fundamental types of sequences are: Strings, lists, tuples.

5.2. Numbers
The numeric category is composed of integers, the numbers of
floating point and complex numbers. The classes int, float, and are defined.
complex in Python.

The function type() allows you to check what type of data a variable belongs to.
or a value; and the isinstance() function to check if an object belongs to a
particular data type.
a = 5
type(a)

b = 2.0
type(b)

c = 1 + 2j
isinstance(c, complex)

An integer can be of any length, it is only limited by the


available memory.

Examples of mathematical operations:


2 + 3
5
>>> 3 - 2
1
2 * 3
6
>>> 3 / 2
1.5

Integers and floating points are separated by decimal points. 1 is an integer,


1.0 is a floating point number.

Python calls any number with a decimal point: a floating point number
aunt. This term is used in most programming languages, and
It refers to the fact that a decimal point can appear in any position.
of a number. This type of data is accurate up to 15 decimal places.

Complex numbers are written in the form,x+ yj wherexit is the real part
ey it is the imaginary part.

Yessenia Portal Machuca 31 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Examples.
a = 1234567890123456789
a
1234567890123456789

b = 0.1234567890123456789
b
0.12345678901234568

c = 1+2j
c
(1+2j)

Note that the variable float b was truncated.

5.3. Sequences
5.3.1. Strings
In Python, a string is a predefined object that contains a series of characters.
teres.

Single or double quotes are used to represent strings. Multi-line strings


lines can be denoted by triple quotes, ' or "".
This is a string
a
multiline

This is a string.
This is also a string.

This flexibility allows the use of quotes and apostrophes within strings:
I can say, 'Python is my favorite language!'
The language 'Python' is named after Monty Python.
One of the strengths of Python is its diverse and supportive community.

A variable can be created that contains a string data type value.


using the equal assignment operator (=). For example:
name =’Harsh’

The value of this string can be displayed simply by writing the name of the
object in the command line. or using the print() function.
>>>name Harsh
print(name)

Yessenia Portal Machuca 32 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Concatenate String: To concatenate strings, Python uses the plus sign +. And the
operator*, concatenates a string given the number of times. For example, 3*name
I would say "harsharshharsharsharsharsh." For example:
name = name + 'arsh'
print(name)
Harsharsh

3*name
HarshHarshHarsh

Blank spaces or new lines: to add a blank space you can


open and close quotes " ", to add a watermelon to the text the command is used, and
to add a new line in a string use \n. Examples:
Languages: Python C JavaScript
Languages:
Python
C
JavaScript

Python can look for additional whitespace on the right and left sides
from a string. To ensure that there are no white spaces in the
right end of a string, use the rstrip() method.
>>> favorite_language =’python ’
>>> favorite_language
python
>>> favorite_language.rstrip()
python
>>> favorite_language
python

You can also remove the white spaces from the left side of a string
using the lstrip() method or removing whitespace from both sides of the
you can use strip():
>>> favorite_language =’ python ’
>>> favorite_language.rstrip()
python
>>> favorite_language.lstrip()
python
favorite_language.strip()
python

Yessenia Portal Machuca 33 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Indexing: the value of a particular position in a string can be shown


through indexing, which has the following syntax.
<name of the String>[index]

For example, if we want to know the first character of the string, we should write
the following code:
print(name[0])
H

Negative indexing: in a string it refers to the character present at the nth


position starting from the end. Example:
print(name[-2])
s

Length of a string: this can be found using the function len().


which returns the length of the string.
len(name)
5

Cutting a string: it refers to removing some part of the string. For example:
>>>name =’Sonam’
>>>name
Sonam

To extract the part after the first letter, or after the first two.
letters we can write:
>>> name1=name[1:]
>>> name1
Onam

>>>name = name[2:]
>>>name
I

The string in Python is not mutable; that is, once defined, the value of a
the string cannot be changed. Just like with the list and the tuple, the slicing operator
It can be used with a string. Strings are immutable.
Hello world!

s[4] = 'o'
print(s[4] = , s[4])

world
print(s[6:11] =

Error generation
Strings are immutable in Python
s[5] =’d’

Yessenia Portal Machuca 34 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Avoiding Type Errors with the str() Function: Python knows that the variable
it could represent the numerical value 23 or the characters 2 and 3. When you use nume-
integer values within strings like this, you need to specify explicitly that
you want Python to use the integer as a string of characters. It can.
do this by wrapping the variable in the str() function, which tells Python that
represente valores que no sean strings como strings. Ejemplo:
age = 23
message ="Happy "+str(age) +"rd Birthday!"
print(message)

5.3.2. List
A list is an ordered sequence of elements. It is one of the data types.
most used in Python and it is very flexible. It is not necessary for all the elements
that a list contains elements of the same type.

Declaring a list is quite simple. The elements separated by commas are


include in brackets [].
>>> a = [1, 2.2, 'python']

∗ A list can be a collection of homogeneous elements, for example:


[1,2,3]
∗ It can contain different elements (heterogeneous), for example: [1, "abc,"
2.4].
∗ A list can be empty[]
∗ Finally, a list can also contain a list.

Indexing: the brackets operator [] is used to extract an element or a range


of elements of a list. Write the name of the list followed by the index of the
element between brackets. For example, if the list named A contains [1, 2,
3], then listA[1] contains the element '2' and listA[-1] contains the
element "3".

Remember: In Python, the index starts from 0.

For example.
a = [5,10,15,20,25,30,35,40]

a[2] = 15
print(a[2] = , a[2]

# a[0:3] = [5, 10, 15]


print(a[0:3] =

# a[5:] = [30, 35, 40]


print(a[5:] =

Yessenia Portal Machuca 35 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Use of individual values from a list: Individual values can be used


individuals from a list as I would with any other variable. For example, one would
you can use concatenation to create a message based on a value of a
list. Example:
bicycles = [’trek’,’cannondale’,’redline’,’specialized’]
message ="My first bicycle was a "+ bicycles[0].title() +"."
print(message)

Lists are mutable, that is, the value of the elements in a list can
to change oneself.
a = [1,2,3]
a[2]=4
>>> a
[1, 2, 4]

Modification of list elements: the syntax to modify an element


it is similar to the syntax for accessing an element of a list. To change a
element, use the name of the list followed by the index of the element you want
change and then provide the new value you want for that
element. For example:
motorcycles = [’honda’,’yamaha’,’suzuki’]
print(motorcycles)

motorcycles[0] =’ducati’
print(motorcycles)

The output shows that the first element has been modified and that the rest of the
the list remains the same:
[’honda’,’yamaha’,’suzuki’]
[’ducati’,’yamaha’,’suzuki’]

You can modify the value of any element in a list, not just the first one.
element.

Add elements to a list: It is possible to add a new element to a list.


using the append() function. When adding an element to a list, the new element
added to the end of the list.
motorcycles = [’honda’,’yamaha’,’suzuki’]

[Link]('ducati')
print(motorcycles)

[’honda’,’yamaha’,’suzuki’,’ducati’]

Yessenia Portal Machuca 36 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

If you need to add a new element at any position in the list using
the function insert(). This is done by specifying the index of the new element and the
value of the new position. Example:
motorcycles = [’honda’,’yamaha’,’suzuki’]
[Link](0,'ducati')
print(motorcycles)

[’ducati’,’honda’,’yamaha’,’suzuki’]

Remove elements from a list: you can use the del function, if you know the
position of the element you want to remove from a list. Example:
motorcycles = [’honda’,’yamaha’,’suzuki’]
print(motorcycles)

delmotorcycles[0]
print(motorcycles)

If you want to remove the last element from the list, you can use the pop() function.
which also allows you to work with that element after deleting it.
motorcycles = [’honda’,’yamaha’,’suzuki’]

popped_motorcycle = [Link]()
print(motorcycles)

print(popped_motorcycle)

The output shows that the value of the last element was removed from the end of the
list and is now stored in the variable popped_motorcycle.
[’honda’,’yamaha’]
suzuki

You can use pop() to remove an element from a list at any position.
including in parentheses the index of the element you want to delete.
motorcycles = [’honda’,’yamaha’,’suzuki’]
first_owned = [Link](0)

If you do not know the position of the value you want to remove from a list, you can use
the method remove(). This function removes only the first occurrence of the value
specified.
motorcycles = [’honda’,’yamaha’,’suzuki’,’ducati’]

too_expensive =’ducati’
[Link](too_expensive)

Yessenia Portal Machuca 37 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Sorting a list
A list can be sorted temporarily using the sort() method. For example:
organize alphabetically.
cars = [’bmw’,’audi’,’toyota’,’subaru’]
[Link]()
print(cars)
[’audi’,’bmw’,’subaru’,’toyota’]

This function can also sort in reverse, using the argument reverse =
Trueal methodsort(). For example:
cars = [’bmw’,’audi’,’toyota’,’subaru’]
[Link](reverse=True)
print(cars)
[’toyota’,’subaru’,’bmw’,’audi’]

Once the function is executed, the order of the list changes permanently. Without
embargo, if a temporal order is required, you can use the sorted() function.
example:
cars = [’bmw’,’audi’,’toyota’,’subaru’]
print(Here is the original list:
print(cars)
Here is the original list:
["bmw","audi","toyota","subaru"]
print(Here is the sorted list:
print(sorted(cars))
Here is the sorted list:
[’audi’,’bmw’,’subaru’,’toyota’]

The sorted() function can also accept a reverse = True argument if


wants to display a list in reverse alphabetical order.

Yessenia Portal Machuca 38 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

[Link]
You untuple a sorted sequence of elements like in a list. The only
the difference is that tuples are immutable, that is, once created they cannot
be modified.

Tuples are used to protect data from being written and are usually more
faster than lists, since they cannot be changed dynamically.

A tuple can also contain heterogeneous elements.

It is defined in parentheses () where the elements are separated by commas.


>>> t = (5, 'program', 1+3j)

The bracket operator [] is used to extract elements, but we cannot change


its value.
t = (5, 'program', 1+3j)

Here an error occurs because tuples are immutable


t[0] = 10

The operator '+' in a tuple concatenates two tuples. For example:


tup1= (1,2)
tup2=(3,4)
tup3 = tup1 + tup2

tup3
(1, 2, 3, 4)

Tuples are extremely useful in operations like swapping, etc.


Swapping in Python is as simple as assigning (a, b) to (b, a).

For example:
num1= 2
num2= 3

print(The numbers entered are num1 & num2


(num1, num2) = (num2, num1)

print(The numbers now are num1 & num2

Output

The numbers entered are 2 and 3


The numbers now are 3 and 2
>>>

Yessenia Portal Machuca 39 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Tuples and multidimensional lists


You can make lists (lists of lists) and multidimensional tuples. For example,
a list made up of three lists.
In [40]: a = [[3, 9], [8, 5], [11, 1]]

Such constructions can be useful for making tables and other structures.
you can access the different elements of a list with a direct extension of the
indexing scheme that we have been using.

Examples:

The first element of the list is:


In [46]: a[0]
Out[46]: [3, 9]

El segundo es: que es 8, como se ilustra a continuación:


In [47]: a[1]
[8, 5]

The first element of the second element of the list is:


In [48]: a[1][0]
8

The second element of the third element of the list is:


In [49]: a[2][1]
Out[49]: 1

Multidimensional tuples work exactly like multi-dimensional lists.


two-dimensional, except that they are immutable.

5.4. Sets
A set is an unordered collection of unique items. A set is
defined by comma-separated values within braces {}. The items in a
set not organized.
a = {5,2,3,1,4}

Printing the set variable


print(a = , a

We can perform set operations such as union and intersection of sets.


A set has unique values. They eliminate duplicates.
>>> a = {1,2,2,3,3,3}
>>> a
{1, 2, 3}

Yessenia Portal Machuca 40 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Dado que, el conjunto es una colección desordenada, la indexación no tiene signi-


ficado. Por lo tanto, el operador corchetes[]no funciona.
>>> a = {1,2,3}
a[1]
Traceback (most recent call last):
File "<string>", line 301, in run code
File "<interactive input>", line 1, in <module>
TypeError:’set’objectdoesnotsupport indexing

5.5. Diccionario
A dictionary is an unordered collection of key-value pairs.

It is generally used when we have a large amount of data. Dictionaries


they are optimized to retrieve data. We must know the key to recover
the value.
In Python, dictionaries are defined with curly braces {} and each element is a pair.
in the key:value format. Key and value can be of any type.
d = {1:’value’,’key’:2}

The key is used to retrieve the respective value. But not the other way around.

print(d[1] = , d[1])
d[1] = value

A key-value pair is a set of values associated with each other. Each value is
connected to its value by two points, and the individual key-value pairs are
separated by commas.

Add new key-value pairs: dictionaries are dynamic structures and


You can add new key-value pairs to a dictionary at any time. For
example, to add a new pair, you must provide the name of the dictionary followed
of the new key in brackets along with the new value.
Python does not care about the order in which it stores each key-value pair; it only cares
The connection between each key and its value is important.

Start with an empty dictionary: to begin filling an empty dictionary,


define a dictionary with a set of empty keys and then add each pair
key-value on its own line. For example, here is how to build the dictionary
colors_0 using this approach:
colors_0 = {}
colors_0[’color’] =’green’
colors_0[’points’] = 5
print(colors_0)

Yessenia Portal Machuca 41 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Modification of values in a dictionary: to modify a value in a


diccionario, dé el nombre del diccionario con la clave entre corchetes y luego el
new value you want to associate with that key. For example:
colors_0 = {’color’:’green’}
colors_0[’color’] =’yellow’

Removal of key-value pairs: when you no longer need a fragment of


information stored in a dictionary can use the for statement
completely remove a key-value pair. All you need is the name of the
dictionary and the key you want to delete. For example,
colors_0 = {’color’:’green’,’points’: 5}
delcolors_0[points

5.6. Conversion between data types


We can convert between different types of data using different
conversion functions such as: int(), float(), str(), etc.
>>>float(5)
5.0

The conversion defloat will truncate the value (bring it closer to zero).
10
10
>>>int(-10.6)
-10

The conversion to and from the string must contain compatible values.
>>>float('2.5')
2.5
25
25

We can even convert one sequence to another.


set([1, 2, 3])
{1, 2, 3}
tuple({5,6,7})
(5, 6, 7)
>>>list('hello')
hello

To convert to a dictionary, each element must be a pair


>>>dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>>dict([(3,26),(4,44)])
{3: 26, 4: 44}

Yessenia Portal Machuca 42 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

6. Input and Output


Python provides 2 input methods: from the computer keyboard and
the input data file, there are also two output forms: the screen of
computer and the output data file. Each of these forms will be reviewed.
entry and exit.

6.1. Input Function


The input() function is used to obtain input from the user and assign it to a
assigning a value to a variable is useful for taking user input

The syntax of input() is:


strname =input("prompt")

where we prompt the string that we want to display on the screen. When it is executed
the input function prints on the computer screen the text in the quotes
and waits for user input. The user types a string.
num = input('Enter a number: ')
Enter a number: 10

num
10

Here, it is shown that the entered value is a string, not a number.


to convert this into a number we can use the int() or float() functions.
int(10
10

float(’10’
10.0

6.2. File input: importation


There are several ways to read data in Python from an external file. The way
easier to read a text or csv file. is to use the function loadtxt() of the
paqueteNumPy. Se ilustra un ejemplo a continuación, donde se lista los nombres
from the columns to the left of the assignment operator '='.
import numpy as np
dataPt, time, height, error = [Link]("[Link]", skiprows=5,
unpack=True)

Yessenia Portal Machuca 43 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

The loadtxt() function has the following main arguments:

∗ enter the name of the file to read.


∗ skiprows indicates the number of lines to omit at the top of the file,
sometimes called the header.
∗ unpack, indicate if the data can be read directly into the arrays
unpack the data.
∗ usecols, you can specify the columns you want to read by writing the
position of the same.
∗ delimiter, indicate if the columns are separated by commas in the case of
csv [Link] for blank spaces in the case of txt files.
For this code to run correctly, the file to be imported must be in
the current working directory of the IPython interpreter, otherwise, it is needed
specify the path of the directory with the name of the file.
When importing files with a csv extension, the argument must be configured
delimiter=',', as shown below:
dataPt, time, height, error = [Link]("[Link]", skiprows=5,
unpack=True,delimiter=','

6.3. Output using the print() function


The print() function is used to send data to the standard output device
(screen).
The complete syntax of the print() function is
print(*objects, sep=' ', end='\n',file=[Link], flush=False)

where:

∗ objects the (the) value(s) to print.


∗ separator is used between values. By default, it becomes a
character of space.
∗ Una vez impresos todos los valores, se imprimeend. Esto por default establece
a new line.
∗ files the object where values are printed and their default value
[Link](screen).

Example:
print(’This sentence is output to the screen’)
This sentence is output to the screen

a = 5
print(The value of a is
The value of a is 5

Yessenia Portal Machuca 44 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Examples of configuring the argument of a function:


print(1,2,3,4)
# Output: 1 2 3 4

print(1,2,3,4,sep=’*’)
# Output: 1*2*3*4

print(1,2,3,4,sep=#&
1#2#3#4&

Output format: the method [Link]() will allow us to format an output


to make it look attractive.

This method is visible to any string object.


x = 5; y = 10
print(The value of x is {} and the value of y is {}.format(x,y)
The value of x is 5 and the value of y is 10

Here the keys {} are used as placeholders.

We can specify the order in which it is printed using numbers (index of


tuple).
print(I like {0} with {1}.format(["bread","butter"]
I like bread with butter

We can even use keyword arguments to format the string.


print(Hello {name}, {greeting}.format(greeting =Good morning, name = 'Miguel'
Hello Miguel, Good morning

We can even format strings like the old printf() style used in
the programming language C. We use the % operator to achieve this.
x = 12.3456789
print(The value of x is %3.2f
The value of x is 12.35

print(The value of x is %3.4f%x


The value of x is 12.3457

Yessenia Portal Machuca 45 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

6.4. Salida de archivos: exportación


Just like in importing, there are many functions to export data in
Python. Nonetheless, the simplest way to write data files in
text or csv format, is to use the function savetxt() from NumPy. The general syntax
de es:
savetxt(filename, array, fmt=" %0.18e"
delimiter=" ", newline=" \n", header="",
footer="", comments="#")

Where,

∗ filename, indicates the name of the data file to be created, which must be
create in quotes. If the file name already exists, it will be overwritten.
∗ array, indicate the list of column names of the data to be exported,
use the zip function if you want to package the columns into one.
∗ fmt is an optional argument where you can configure the number of
decimal digits in exponential notation (e) or in float notation (f).
∗ delimiter, by default a blank space is left when it comes to
txt files. and a comma must be configured when it comes to csv files.
∗ header is a string variable that allows you to write the header text
about the data.

Example of how to export to a text file.


import numpy as np
[Link]("[Link]", list(zip(dataPt, time, height, error)),
%12.1f

Example of how to export in a CSV file.


[Link]('[Link]',
list(zip(dataPt, time, height, error))
fmt=" %0.1f", delimiter=", "

Yessenia Portal Machuca 46 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

7. Statement, indentation, and comments


7.1. Sentence
The instructions that a Python interpreter can execute are called statements.
instructions(statements).
For example

∗ a=1 is an assignment statement.


∗ The if statement, the for statement, the while statement, etc. are statements
of control.

7.1.1. Multiline statement


The end of a statement is marked by a newline character.
However, we can make a statement extend over multiple lines.
with the line continuation character (\
of explicit line. For example:
a = 1 + 2 + 3 + \
4 + 5 + 6 +
7 + 8 + 9

A continuation of the line is implicit within parentheses(), brackets[]


and keys{}. For example, we can implement the above multiline statement
how
a = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9

likewise
colors = [’red’,
blue
green

We can put several statements on a single line using a semicolon (;)


a = 1; b = 2; c = 3

7.2. Indentation
In programming, indentation means moving a block of text to the right.
by inserting spaces or tabs, in order to separate it from the left margin and
distinguish it better from the adjacent text; in the field of printing, this concept
It has always been called bleeding or indentation.

Most programming languages like C, C++, Java use curly braces {}


To define a code block, Python uses indentation.

Yessenia Portal Machuca 47 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

A block of code (the body of a function, loop, etc.) begins with an indentation
and ends with the first line flush left. The amount of indentation depends on the
programador, sin embargo, debe ser consistente en todo el bloque.

In general, 4 spaces are used for indentation and tabs are preferred.
Here is an example.
for i in range(1, 11):
print(i)
ifi == 5:
break

The use of indentation makes the code look clean and organized. This provides
as a result, programs that look similar and consistent.

The indentation can be ignored in the continuation of the line; however, it is a


Good idea to always indent; it makes the code more readable.
For example:
ifTrue:
print(Hello
a = 5

y
ifTrue:print(Hello); a = 5

Both are valid and do the same thing; however, the first style is clearer.

Incorrect indentation will result in an IndentationError.

In Python, indentation is used to detect the presence of loops; loops


In Python, they do not start or end with delimiters or keywords.

7.3. Python Comments


Comments allow you to describe what is happening inside a program,
as their programs become longer and more complicated, you must add
notes within their programs that describe their general approach to the problem that
is resolving, so it generally serves 1) to a person who looks at the
source code is easy to understand, and 2) to the one who built the program,
when I might forget the key details of the program I wrote in a month.

In Python, the hash symbol (#) is used to start writing a comment, which
write after a hash mark in your code, it is ignored by the interpreter
Python.

Example:
This is a comment
Print Hello
print(Hello

Yessenia Portal Machuca 48 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

7.3.1. Multiline comments


One way to create comments that extend over multiple lines is by using a
hash (#) at the beginning of each line. For example:
This is a long comment
and it extends
multiline

Another way to do this is to use triple quotes, either '' or "".

These triple quotes are generally used for multi-line strings, like this
as for multi-line comments. Unless they are docstrings, no
they do not generate any additional code.

This is also a
perfect example of
multi-line comments

7.3.2. Docstring
Docstring is the abbreviation for documentation string.

A docstring is a string that appears as the first statement in a module,


function, class or method definition. In it, you should write what it does.
function/class.

Triple quotes are used when writing docstrings.


defdouble(num):
Function that returns a double value
return2*num

Docstring allows us to use the __doc__ attribute of the function.


Return the double precision floating point representation of the number.
Function that returns a double value

All documentable objects (modules, classes, methods, and functions) have


with an attribute __doc__ which contains its respective documentation comment
station.

Yessenia Portal Machuca 49 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

8. Control Statements
8.1. Selective statements: If, If-Else, and If-Elif-Else
Selective statements are an integral part of programming, for decision making.
of decisions. Python recognizes a block of code through indentation.
Indentation determines the beginning and the end of a block in Python. Therefore, it is
It is important to be careful with indentation, otherwise an error will occur.
code output.
The if <condition> statement is followed by a colon.

There is no need for parentheses for this test condition. Although including the
The test in parentheses will not result in an error.

An 'if' can have any number of nested 'if' statements inside.

The condition of the selective statement must result in a True or False.

8.1.1. Selective Sentence if


Syntax.
if test_expression:
sentence(s)

Example
If the number is positive, the appropriate message is printed.

num = 3
ifnum > 0:
print(num,it is a positive number.
print("Esto se imprime siempre.")

num = -1
ifnum > 0:
print(num,it is a positive number.
print(This is always printed too.

When running the program, the output is:


3 is a positive number
This always prints.
This is always printed as well.

8.1.2. Selective Statement if...else


Syntax
if test_expression:
sentence(s)1
else:
sentence(s)2

Yessenia Portal Machuca 50 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Example.
Program that checks if the number is positive or negative
And show an appropriate message

num = 3

Try these two variants as well.


# num = -5
# num = 0

ifnum >= 0:
print(Positive Number or Zero
else:
print(Negative Number

8.1.3. if...elif...else statement


If there are multiple conditions and the results decide the action, then it can be
use an if...elif...else statement.

Syntax
if test_expression1:
sentence(s)1
else if test_expression2:
sentence(s)2
else:
sentence(s)3

8.1.4. Nested if statements


Example.
In this program, a number is entered and verified.
If the number is positive, negative, or zero
And an appropriate message is displayed
This time nested ifs are used

num = float(input("Enter a number: "))


ifnum >= 0:
ifnum == 0:
print(Zero
else:
print(Positive number
else:
print(Negative number

Yessenia Portal Machuca 51 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

8.1.5. Ternary Operator


The conditional statements explained in the previous section are important.
to write any program that contains conditions. However, the code
It can be further reduced using the ternary statements provided by
Python. The ternary operator performs the same task as the if-else construct.

Example: Find the largest of the three numbers entered by the user, using
a ternary operator.
Ternary Operator
a = int(input('Enter the first number :'))
b = int(input('Enter the second number :'))
c = int(input('Enter the third number :'))

big = (a if (a > c) else c) if (a > b) else (b if (b > c) else c)


print(The largest of the three numbers is str(big))

8.2. Iterative Statements


Many situations require us to repeat a specific task many times,
how to calculate the value of a function, to print a pattern or simply to
to repeat something.

Looping means repeating a series of statements until a condition


be true.

In general, the repetition of a block requires the following:

Deciding what will be repeated: the set of


statements.

The test condition will be repeated or the


number of times it is repeated
set of statements.

Special cases in which the loop


breaks or continues, escaping from
certain sentences.

Yessenia Portal Machuca 52 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Python offers two types of loops: for and while.

While is the most common loop construction in Python.


It is generally used to process lists, tuples, matrices, etc.
Range(n) means values from 0 to (n - 1).

Range(m, n) means all values of ma(n - 1).

8.2.1. Iterative Statement for


Syntax
sequence management:
sentence(s)

For example
Program that finds the sum of all the numbers in a list
List of numbers
numeros = [6, 5, 3, 8, 4, 2, 5, 4, 11]

variable that will store the sum (accumulator)


sum= 0

iteration over the list


forvalinnumeros:
sum = sum + val

The sum is 48 you will find some of these libraries


extremely useful and easy to use.
print(The sum is sum)

Program execution
The sum is 48

The function range()

Example 1.
range(0, 10)
print(range(10))

# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(10)))

# Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))

# Output: [2, 5, 8, 11, 14, 17]


print(list(range(2, 20, 3)))

Yessenia Portal Machuca 53 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Example 2.
Program to iterate through a list using indexing

genre = [’pop’,’rock’,’jazz’]

iterate over the list using an index


for i in range(len(genre)):
print(I like the

Program execution
I like pop
I like rock
I like jazz

For loop with else

For example.
digits = [0, 1, 5]
forinindigits
print(i)
else:
print("No items left."

Execution of the program


0
1
5
No items left.

8.2.2. Iterative Statement while


Syntax
whiletest_expression:
sentence(s)

For example.
Program that adds the natural numbers from 1 to n
# sum = 1+2+3+...+n
n = int(input("Enter n: "))
n = 10
initialize sum and the counter
sum= 0
i = 1
while i <= n:
sum = sum + i
i = i + 1 update the counter
print the sum
print(The sum is sum)

Yessenia Portal Machuca 54 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Output.
Enter n: 10
The sum is 55

While statement with else

For example.
Example to illustrate
the use of the else statement
with the while loop

counter = 0

while counter < 3:


print("Inside the loop"
counter = counter + 1
else:
print(Inside the else

Output.
Inside the loop
Inside the loop
Inside the loop
Inside the else

Yessenia Portal Machuca 55 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

9. Functions
9.1. What is a function in Python?
In Python, a function is a group of related statements that perform a
specific task.

Functions help to divide our program into smaller and more manageable parts.
dollars. As our program grows more and more, the functions do too.
more organized and manageable.

Además, evita la repetición y hace que el código sea reutilizable.

9.2. Types of functions


Basically, we can divide functions into the following two types:

[Link] functions (built-in):


Built-in functions in Python.
[Link]-defined functions:
Functions defined by the users themselves. Of which they can be fun-
conventional functions of Lambda functions.

9.2.1. Conventional function


Syntax:
def function_name(arguments):
documentation chain
sentence(s)

where:

The word 'clavedef' marks the beginning of the function header and informs
In Python, a function is being defined.
The name of the function allows it to be identified uniquely.5
3. Arguments, through which we pass values to a function and
declared in parentheses. They can be mandatory or optional.
4. The colon (:) denotes the end of the function header.
5. The documentation string (docstring) is optional to describe what
make the function. The Docstrings are declared between triple quotes and should
appear immediately after the function definition.
6. The body of the function is comprised of one or more statements. The decla-
Indentations must have the same level of indentation (usually 4 spaces).
7. The return statement (optional) allows the function to return a value.

5 The naming of functions follows the same rules for writing identifiers in Python.

Yessenia Portal Machuca 56 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

If a proposed value is specified for a parameter, no should be used.


space on both sides of the equal sign.
def function_name(parameter_0, parameter_1=default value

The same convention should be used for keyword arguments when invoking the
function.
function_name(value_0, parameter_1='value')

Example of a function: 'name'


def greet(name):
This function greets
to the person who is passed
as a parameter
print(Hello,

9.2.2. How to call a function?


Once we have defined a function, we can call it from another function.
program it in the Python interpreter.
To call a function, we simply write the name of the function with
the appropriate arguments in parentheses, which tells Python to execute the
function code.
Example: use the function 'name'
Hello, Paul
Hello, Paul. Good morning!

Argumentation errors occur when too little or too much is provided.


arguments that a function needs to perform its work.

9.2.3. The return statement


The return statement allows for an immediate exit from the function in which it is.
find, that is to say, it is used to exit a function and return to the place from
where the function was called.

The following diagram illustrates how a function works in Python

Yessenia Portal Machuca 57 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Syntax
return[expression_list]

This statement may contain an expression that is evaluated and returns the value.
If there is no expression in the declaration or the return statement is not present,
the function will return the object None.

For example:
def absolute_value(num):
This function returns the value
absolute of the entered number
ifnum >= 0:
returnnum
else:
return-num

# Output: 2
print(absolute_value(2))
Output: 4
print(absolute_value(-4))

9.2.4. Types of function arguments


Positional arguments: When a function is called in Python, it must ...
match each function argument with a parameter from the definition that is
it performed the function. The simplest way to do it is based on the order of the
provided arguments. The paired values in this way are called
positional arguments.
deftipo_derivados(tipo,subtipo)
Information about financial derivatives
print(One of the types of derivative assets is:
print(It is categorized into subtypes:

tipo_derivados(’Opciones’,’Europeas’)

Keyword argument: A keyword argument is a name-value pair that is


declare in a function. The name and the value are directly associated within the
argument, so that when the argument is passed to the function, there is no
confusion. When using keyword arguments, make sure to use the names.
exactly the parameters in the definition of the function.
deftipo_derivados(tipo,subtipo)
Information about financial derivatives
print( One of the types of derivative assets is:
print(It has subtypes:

tipo_derivados(tipo=’Opciones’,subtipo=’Europeas’)

Yessenia Portal Machuca 58 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Default Arguments: When writing a function, you can define a default value.
for each parameter. If a value is provided for an argument when invoking the
function, Python uses the value of the argument. If not, it uses the value by
default of the argument. The use of the proposed values can simplify
the use of the function and clarify the ways in which it is usually used
the functions. When using default values, any argument with
a default value must appear after all non-default arguments
They have default values. This allows Python to continue interpreting
correctly the positional arguments.
derived_type(subtype,type=Options
Information about financial derivatives
print(One of the types of derivative assets is:
print(It has subtypes:

tipo_derivados(subtipo=’Europeas’)

Optional arguments: Sometimes it makes sense to make an argument optional.


functional so that those who use the feature can choose to provide information
additional only if they wish so. You can use default values to make a
argument is optional.

Example:
We define the name format function, where the second name is optional.
def get_formatted_name(first_name, last_name, middle_name=’’):
Return a full name, neatly formatted.
ifmiddle_name:
full_name = first_name +’ ’+ middle_name +’ ’+ last_name
else:
full_name = first_name +’ ’+ last_name
returnfull_name.title()

musician = get_formatted_name(’jimi’,’hendrix’)
print(musician)

musician = get_formatted_name(’john’,’hooker’,’lee’)
print(musician)

To make the middle name optional, the argument middle_name was assigned.
a default empty value and what causes the argument to be ignored unless the
user provide a value.

Yessenia Portal Machuca 59 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

9.2.5. Lambda Functions


They are anonymous functions (nameless) that are created quickly and simply,
when performing light actions that only require a small calculation.
They differ from conventional functions because the content of a function
lambda must be a single expression and NOT a block of statements.
Every lambda function can be expressed as a conventional function, but
no vice versa.
Syntax of the Lambda function.
lambdaargumentos: resultado

or also

f = lambda arguments: results

Equivalent to a lambda function

def(arguments):
returnresult

Example.
f=lambda a,b,c=1: (4*a-b)/c

Its equivalent as a conventional function


def(a,b,c=1):
return(4*a-b)/c

9.3. Docstring
The first string after the function header is called a docstring and
it is the abbreviation for documentation chain. It is used to briefly explain,
what a function does.
Although optional, documentation is a good programming practice.
less than I can remember what I ate last week, always document your
code.
In the previous example, we have a string of documents immediately below
from the header of the function.

Generally, triple quotes are used for the documentation string


it can extend up to several lines. This string is available as the attribute
__doc__ of the function.
For example:
print(greet.__doc__)
This function greets
to the person who is passed
as a parameter

Yessenia Portal Machuca 60 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

9.4. Scope and lifespan of variables


The scope of a variable is the part of a program where it is recognized.
variable.

∗ The parameters and variables defined within a function are not visible.
from the outside. Therefore, they have a local reach.

The useful life of a variable is the period during which the variable is out of the
memory.

∗ The lifespan of variables inside a function is always as long as the function


to be executed.

∗ They are destroyed once we return from the function. Therefore, a function
It does not remember the value of a variable from its previous calls.

Here is an example to illustrate the scope of a variable within a function.


defmy_func():
x = 10
print(Value inside the function:

x = 20
my_func()
print(Value outside function:

Exit
Value inside the function: 10
Value outside the function: 20

Regarding the previous example:

∗ We can see that the value of dexes 20 initially. Although the function my_func()
the value of dexa10 changed, it did not affect the value outside of the function.

∗ This is because the variable inside the function is different (local to the
function) that is outside. Although they have the same names, they are two
different variables with a different scope.
∗ On the other hand, variables outside the function are visible from inside.
They have a global reach.
∗ We can read these values from inside the function, but we cannot
change them (write them). To modify the value of the variables outside of the
function, must be declared as global variables using the keyword
global.

Yessenia Portal Machuca 61 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

9.5. Storing your functions in Modules


Una de las ventajas de las funciones es la forma en que separan los bloques de
code of your main program. By using descriptive names for your functions,
your main program will be easier to follow. It is possible to store your functions
in a separate file called module and then import the module into your program
principal.

An import statement tells Python to make the code of


a module, in the currently running program file.

Store your functions in a separate file: it allows you to hide the details of
code of your program and focus on its high-level logic. It also allows
reuse functions in many different programs.

How to create a module?

∗ A module is a file that ends in .py that contains the code that
you want to import into your program. The following section will describe in more detail
the modules.
∗ A module is created that contains the function make_pizza(), saving it in
the file [Link]

[Link]
def make_pizza(size, *toppings):
Summarize the pizza we are about to make.
print(Making a str(size) +
-inch pizza with the following toppings:
fortoppingintoppings
print(-

main_program.py
importpizza

pizza.make_pizza(16,’pepperoni’)
pizza.make_pizza(12,’mushrooms’,’green peppers’,’extra cheese’)

∗ Any function defined in the file [Link] will be available in:


main_program.py once the module has been imported.
∗ To invoke a function from an imported module, write the name of the
module that has been imported, followed by the name of the function, separated by
a point. The syntax is as follows:
module_name.function_name()

∗ This first approach to importation makes all the functions of


module is available in your program.

Yessenia Portal Machuca 62 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

10. Classes and objects


In the object-oriented paradigm, the program revolves around an object and therefore
thus the type of programming is called object-oriented programming.

10.0.1. What is an Object?


An object is an instance of a class. Objects interact with each other and perform
the work.
Generally, a class can have any number of objects, and it is possible
to form a series of objects.

10.0.2. What is a Class?


A class is an entity that is relevant to the problem at hand and has
Physical limits. The selection of attributes will determine the physical limits of the class.

One can perceive a class as a prototype, which has attributes and behavior.
treatment. Attributes generally store data and behavior is
implement through functions.
The attributes represent the characteristics of the entity to which they pertain.

Functions implement the behavior of a class. In a class, it can...


have any number of functions, each of which performs a task in
particular.
Definition of a class: in Python, a class can be defined using the
keyword class, followed by the name of the class. Just like in the
functions, one must take into account the indentation when defining a class. The syntax is
the following:
class<name_the_class>:
def<function_name>(<argument>):
...
<members>

Below is an example of a class (movie) and objects (three movies).

Movie
Class

The fault in
Love actually Sarat
our stars

Objects

Yessenia Portal Machuca 63 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

The attributes and behavior of a are detailed below.


class. It shows two functions: getdata() and putdata(). The function getdata()
ask the user for the values of the variables and the function putdata() will display them
data.

movie
name
Name year
genre
director
producer Class
Attributes actors
music director
story writer
getdata()
Behaviour putdata()

Example: European Options Class


class Binomial European Option (Stock Option):

def __setup_parameters__(self):
Required calculations for the model
self.M = self.N + 1 # Number of terminal nodes of tree
self.u = 1 + [Link]# Expected value in the up state
self.d = 1 - [Link] # Expected value in the down state
[Link] = ([Link](([Link])*[Link]) -
self.d) / (self.u-self.d)
[Link] = 1 - [Link]

def_initialize_stock_price_tree_(self):
Initialize terminal price nodes to zeros
[Link] = [Link](self.M)

Calculate expected stock prices for each node


for i in range(self.M):
[Link][i] = self.S0 * (self.u ** (self.N - i)) * (self.d ** i)

def_initialize_payoffs_tree_(self):
Get payoffs when the option expires at terminal nodes
payoffs = [Link](
0, ([Link]-self.K) if self.is_call
else([Link])

return payoffs

Yessenia Portal Machuca 64 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

11. Packages
11.1. What are packets?
We usually do not store all our files on our computer.
the same location. We use a well-organized directory hierarchy to
facilitate access.

Similar files are saved in the same directory, for example, we can
keep all songs in the 'music' directory. Just like this, Python
packages are to directories and modules are to files.

As our application program grows in size with many modules-


we place similar modules in one package and different modules in packages
different. This makes a project (program) easy to manage and conceive
currently clear.

Similarly, as a directory can contain subdirectories and files, a package


Python can have subpackages and modules.

A directory must contain a file named __init__.py for Python


I considered it as a package. This file can be left empty, but general-
We placed the initialization code for that package in this file.

For example, suppose a game is being developed, a possible organization of


packages and modules could be the one shown in the following figure.

Yessenia Portal Machuca 65 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

11.2. The Scientific Stack


There is a certain set of packages that are collectively referred to as the stack.
scientific. The following packages are described:

1. NumPyprovides a multidimensional array object to store da-


homogeneous or heterogeneous sets; also provides functions/methods
optimized for creating and manipulating (indexing, logical operations, arith-
metrics, trigonometric, among others) this array object, as well as a am-
special functions collection, statistical functions and generators
of random numbers. You can find more information about NumPy at
[Link]

2. Pandasthis package is based on NumPy which provides a powerful con-


data analysis toolkit; it is closely integrated
with matplotlib for plotting and PyTables for storage
data recovery. You can find more information about Pandas at
[Link]

[Link] a wide range of mathematical functions and routines


numerical for Python. SciPy makes extensive use of NumPy arrays,
so when you import SciPy, you should always also import NumPy.
In addition to providing basic mathematical functions, SciPy provides
Python wrappers for numerical software written in other languages, such as
Fortran, C or C++. A 'wrapper' provides a Python interface.
parent and easy to use. SciPy greatly extends the power of Python and it
saves the hassle of writing software in Python that someone else has already done
written and optimized in some other programming language. You can find
more information about SciPy at[Link]

[Link] is the standard Python package for making bidi graphics


two-dimensional (2D) and three-dimensional (3D), which makes extensive use of
the NumPy arrays. You can find more information about matplotlib at
[Link]

[Link] is a popular container for the Alma library.


HDF5 data management. It is a library for implementing operations
disk-based I/O optimized in a database / format
of hierarchical file. You can find more information about matplotlib at
[Link]

[Link]:it is a package that provides classes and modules for the


model estimation and statistical tests. For more details, refer to
[Link]

Yessenia Portal Machuca 66 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

11.3. What are modules in Python?


Modules refer to a file that contains statements and Python definitions.

A file that contains Python code, for example: [Link], is called a m-


duo and its module name would be example.

We use modules to divide large programs into small manageable files.


and organized. In addition, the modules provide code reuse.

We can define our most used functions in a module and import it, in
place to copy your definitions into different programs.
Let's see another example of how to create a module. We write the following and save it.
we give as [Link].
Python Modulo example
defadd(a, b):
This program adds two numbers and returns the result.
result = a + b
returnresult

∗ We have defined a function add() within a module called example.


∗ The function takes two numbers and returns their sum.

11.4. How to import modules in Python?


We can import the definitions from one module to another module or to the interpreter.
interactive puppet in Python.

We use the keyword import to do this.

To import our previously defined module example, we write the following


Next in the prompt
>>>importexample

Using the module name, we can access the function using the operation
from point (.). For example:
>>> [Link](4,5.5)
9.5

Python has a large number of standard modules available.

∗ You can consult the complete list of standard Python modules and for
what they are for. These files are located in the directory Lib within the
location where Python was installed.

∗ Standard modules can be imported in the same way as you import


our user-defined modules.

There are several ways to import modules. The ones described below:

Yessenia Portal Machuca 67 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

11.5. Import judgment


We can import a module using the import statement and access the defi-
notions within it using the dot operator as described above.
For example:
Example of using import statement
# to import the math module

import math
print(The value of pi is

When you run the program, the output will be:


The value of pi is 3.141592653589793

11.6. Import with renaming


You can provide an alias for the name of a module. Give a module an alias.
short, it allows you to call the module functions more quickly. Redirects
your attention from the name of the module and allows you to focus on the names
descriptive of their functions.

If the name of a function being imported may conflict with


an existing name in the program or if the function name is long, it can
use a short and unique nickname.

The keyword renames a module or function using the nickname that is


provides.

The general syntax for giving a nickname to a module is:


import module_name as mn

The general syntax for providing a nickname to a function is:


from module_name import function_name as fn

Example of an alias to a module.


Module import with renaming

import math as m
print(The value of pi is

We have changed the name of the module mathporm. This can save us time.
of writing in some cases.

Please note that the name mathno is not recognized within our scope;
both, [Link] invalid, [Link] the correct implementation.

Yessenia Portal Machuca 68 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

11.7. Judgment from ... import ...


We can import specific names from a module regardless of the module.
in its entirety. The general syntax is:
from module_name import function_name

You can also import as many functions as you want from a module, separating them
name of each function with a comma. The syntax is:
from module_name import function_0, function_1, function_2

With this syntax, it is not necessary to use dot notation when calling
to a function.

Example.
importing only pi from the math module

from math import pi


print(The value of pi is

How we only import the attribute of the module. We do not use the dot operator.

Example of how to import multiple functions at once.


from math import pi, e
pi
3.141592653589793

e
2.718281828459045

11.8. Import all functions


You can import all the functions from a module using the asterisk operator.
(*) The general syntax is as follows.
from module_name import *

The asterisk in the import statement tells Python to copy each function
from the module to the current program file. And since all functions are
important, you can call each function by its name without using dot notation
points.

Example.
import all names from the standard math module

from math import *


print(The value of pi is

Yessenia Portal Machuca 69 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

We import all the definitions from the math module. This makes all
the names, except for those that begin with an underscore, should be visible in our
scope.
Importing everything with the asterisk (*) symbol is not a good programming practice.
This can lead to duplicate definitions for an identifier. Also
it hinders the readability of our code.
The best approach is to import the function or functions you want, or to import the
complete module and use dot notation. This leads to clear code
that is easy to read and understand.

11.9. Python module search


When importing a module, Python looks in several places. The interpreter first searches
an embedded module and then (if it does not find it) in a list of directories
defined [Link]. The search is in this order.

∗ The current directory.


∗ PYTHONPATH (an environment variable with a list of directories).
∗ The default directory is dependent on the installation.
>>>importsys
>>> [Link] [’’,
C:\Python33\Lib\idlelib
'C:\Windows\system32\[Link]'
C:\Python33\DLLs
C:\Python33\lib
C:\Python33
C:\Python33\lib\site-packages

We can modify this list to add our own route.

11.10. Reloading a module


The Python interpreter imports a module only once during a session. This
makes things more efficient. Example.
Let's assume we have the following code in a module called my_module.
This module shows the effect
of various imports and reloads

print(This code has been executed

Now we see the effect of multiple imports.


>>> import my_module
This code has been executed

>>>import my_module
>>>import my_module

Yessenia Portal Machuca 70 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

We can see that our code was executed only once. This means that
our module was imported only once.

Now, if our module changed during the course of the program, we would have
that reload it. One way to do this is to restart the interpreter. But this does not
helps a lot.

Python provides a clean way to do this. We can use the function


reload() inside the imp module to reload a module.
>>>importimp
>>>import my_module
This code has been executed

>>> import my_module


>>> [Link](my_module)
This code has been executed

<module 'my_module' from '.\my_module.py'>

11.11. The intertnadir() function


We can use the function dir() to find out the names that are defined.
inside a module.

For example, we have defined an add() function in the example module that
as mentioned earlier.
>>> dir(example)
[’__builtins__’,
’__cached__’,
’__doc__’,
’__file__’,
__initializing__
’__loader__’,
__name__
’__package__’,
add

Here, we can see an ordered list of names (along with add). All the
Other names that begin with an underscore are default attributes
of Python associated with the module (we do not define them ourselves).

For example, the attribute __name__ contains the name of the module.
>>>importexample
>>> example.__name__
example

Yessenia Portal Machuca 71 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

All the names defined in our current namespace can be


find using the function dir() without any argument.
>>> a = 1
hello
>>>import math
>>>dir()
["__builtins__","__doc__","__name__","a","b","math","pyscripter"]

Yessenia Portal Machuca 72 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

12. Numpy Library


12.1. What is Numpy?
NumPyes is a Python package that
It means numerical Python. NumPy
contains multidimensional array objects
files and the routines that process them
array. The package was created by Tra-
vis Oliphant.
One of the greatest advantages of
NumPy (when used together with
SciPyyMATPLOTLIB) is its ability-
dad to perform similar operations
MATLAB boxes.

Some of its most important characteristics include:

∗ It is used for mathematical operations, logical operations, and related operations.


linear algebra.
∗ Numpy is good for indexing
∗ The simplest data structure is an array, which consists of elements.
homogeneous in consecutive memory locations.

Arrays can be multidimensional.

12.2. How can I create an array?


Let's remember that before starting with NumPy, the package must be imported, and of
preference to assign an alias, by convention.
import numpy as np

There are several ways to create an array, Numpy offers different commands for
according to the type of array that is desired to be created. Below are the co-
most important commands to create an array.

Yessenia Portal Machuca 73 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

CommandArray(), is used to convert objects into arrays, for example lists.


and tuples.
mylist = [1, 2, 3]
myarray = [Link](mylist)
myarray

array([1, 2, 3])

The resize() command changes the shape and size of the array.
[Link](3,3)
myarray

array([[1, 2, 3],
[0,0,0]
[0, 0, 0]]

With the command array(), you can create a matrix using a list with repetitions.
actions.
[1, 2, 3, 1, 2, 3, 1, 2, 3]

[1,2,3,1,2,3,1,2,3]

Another way to repeat the elements of an array is to use the repeat command.
[Link]([1, 2, 3], 3)

array([1, 1, 1, 2, 2, 2, 3, 3, 3])

The command ones() returns a new array where its elements are value 1.
You must indicate the number of rows and the number of columns.
[Link]((3, 2))

array([[1., 1.],
[1., 1.]
[1., 1.]

The command zeros() returns a new array where its elements are zeros.
[Link]((2, 3))

array([[0., 0., 0.],


[0., 0., 0.]

The command eye() returns a matrix with a value of 1 on the diagonal and zeros elsewhere.
other positions.
myarray = [Link](3)

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


[0.0,1.0,0.0]
[0.0,0.0,1.0]

Yessenia Portal Machuca 74 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

The command diag() extracts a diagonal or constructs a diagonal matrix.


[Link](myarray)

array([1, 1, 1])

The function arange() helps to record a sequence that has some initial value.
(start), algún valor final (stop), la diferencia entre los términos consecutivos (step)
and the data type (dtype).
[Link](start, stop, step, dtype)

∗ The initial value of the sequence


∗ Stop: The value up to which the sequence is generated (the value is not induced in
himself).
∗ Step: The difference between consecutive values
∗ dtype: The data type
a = [Link](3, 25, 2, int)

a
array([3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23])

The linspace() function divides the given range into a specific number of elements.
and returns the sequence thus formed. The function takes the following parameters:

∗ The first value of the sequence


∗ stop: The last value (included up to the endpoint =False)
∗ The number of objects
∗ If the endpoint is false then the value 'stop' is not included
in the sequence.
∗ If this is true, the size of the step is returned.
∗ dtype: The data type of the elements in the sequence; if not specified,
Then the data type is inferred from the values of start and stop.

d=[Link](11, 27, 11)

d
array([11., 12.6, 14.2, 15.8, 17.4, 19., 20.6, 22.2, 23.8,
25.4, 27.)

In the sequence generated by dividing the range 11-26 into 12 parts, the last argumen-
The result is the step (1.4545454545454546).
f=[Link](11, 27, 11, endpoint=False, retstep=True)

f
[11.0, 12.45454545, 13.90909091, 15.36363636]
16.01010102, 18.27272727, 19.72727273, 21.10101010,
22.63636364, 24.09090909, 25.54545455]), 1.4545454545454546

Yessenia Portal Machuca 75 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

The following describes some of the main functions for modification


array.

Name Description
append() Add an element to the end
insert() Add the element in the specified position. The function
it has two arguments: the first is the element and the
second is the position
count() This counts the number of times the argument is repeated.
pop() Remove the top element of the array
remove() Remove the element from a specified position
reverse() Invert the order of the elements in the array
tostring() Converts the given array into a string

12.3. Combining arrays and data types in NumPy


Example. We create an array of values one, of 2 by 3.
p = [Link]([2, 3], int)

Use the vstack command to combine the arrays in vertical sequence.


[Link]([p, 2*p])

Use the hstack command to combine the matrices in horizontal sequence.


[Link]([p, 2*p])

To see the data type of the elements in the array, we use the command dtype.
[Link]
dtype('int32')

To convert to a specific data type, use astype.


z = [Link]('f')
[Link]

dtype('float32')

Yessenia Portal Machuca 76 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

The following table shows the data types of NumPy.

Tipo de dato Descripción


int8 Byte (-128 to 127)
int16 Integer (-32768 to 32767)
int32 Integer (-2147483648 to
2147483647
int64 Enter
(-9223372036854775808 to
9223372036854775807
unit8 Unsigned integer (0 to 255)
unit64 Integer without sign
float32 (0 to 65535)
float64 Floating point number
which occupies 64 bits of
storage
complex64 64-bit complex number

12.4. Operations
Let's remember that the arithmetic operators are: +,−,∗,/ y∗∗, to perform sums,
subtractions, multiplications, divisions, and powers at the element level. Next
some examples of operations with arrays.
x=[Link]([1, 2, 3])
y=[Link]([4, 5, 6])

print(x + y)Sum
[5 7 9]

print(x - y)Remaining
[-3 -3 -3]

print(x * y)multiplication
[1 2 3] * [4 5 6] = [4 10 18]

print(x / y)division
[1 2 3] / [4 5 6] = [0.25 0.4 0.5]

print(x**2)potentiation
[1 4 9]

r = [Link](y) # dot product 1*4 + 2*5 + 3*6

r
32

Yessenia Portal Machuca 77 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

The command transpose is used to transpose a matrix.


array([[ 4, 5, 6],
[16, 25, 36]]

[Link]

array([[ 4, 16],
[ 5, 25],
[ 6, 36]]

12.5. Broadcasting
Python applies element-wise operations not only in addition or subtraction,
but also in the case of multiplication and division, as shown in the
section 12.4, then the question arises What happens if two arrays are added
different dimensions? Python has a way of dealing with such situations:
This is called Broadcasting.

If you want to add an array A of 4 by 1 with an array B of 1 by 3, you use


broadcasting.

The array A is a two-dimensional array copying the elements of the first column in
all the other necessary columns, in this case 2 additional columns, to equal
the number of columns of array B. Similarly, the array B of columns is
it is converted into a two-dimensional array by copying the elements from the first one
row in all the other rows, in that example 3 additional rows are required. By
both array A and array B have the same dimension.

Yessenia Portal Machuca 78 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

12.6. Aggregate functions


The NumPy module contains many aggregate functions. Below is a menu-
list some statistical functions.

∗ [Link]() finds the sum of the elements of the argument.


∗ [Link]() finds the product of the elements of the argument.
∗ [Link]() finds the mean of the elements of the argument.
∗ [Link]() finds the standard deviation of the elements of the argument
Mento.
∗ [Link]() finds the variance of the elements of the argument.
∗ [Link]() finds the maximum element of the argument. In the case
from a 2D array the axis on which the maximum element is desired also
axis=0 indicates columns and axis=1 indicates rows.
∗ [Link]() finds the minimum element of the argument. Similarly
In the previous function, you can choose the axis in which you want it.
minimum element.
∗ [Link]() finds the position (index) of the maximum element.
∗ [Link]() finds the position of the minimum element.
∗ [Link]() finds the median of the elements of the argument.
∗ [Link]() finds the percentile of the elements of the argument.
Let's look at some examples of integrated mathematical functions:

There is the following array 'm', on which different mathematical functions will be applied.
mathematics.
m = [Link]([-4, -2, 1, 3, 5])

Sum function.
[Link]()

In[1]: 3

Maximum function
[Link]()
In[2]: 5

Minimum function
[Link]()
In[3]:-4

Average function
[Link]()
0.6

Yessenia Portal Machuca 79 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Standard deviation function


[Link]()
3.2619012860600183

For more detail and exploration of the added functions that NumPy has,
enter the link[Link]

12.7. Indexing
The standard indexing syntax in Python is: x[obj], where x is the array.
The selection of elements. There are 3 types of available indexing: basic
slicing, advanced indexing, field access

12.7.1. Basic slicing.


This type of indexing is used for slice targets, integers, lists, or tuples.

The concept of Python indexing [i:j:k] extends to N dimensions; where


it is the initial index, the arrest index, and the stepk= 0). This selects
the elements.

Example 1: The following array 'myarray' is given.


myarray = [Link](13)**2
myarray

array([ 0, 1 4 9, 16, 25, 36, 49, 64, 81, 100, 121, 144])

Let's remember that indexing starts at 0. If it is not provided, the value


default esn(number of elements in the array) fork >0y-n-1para k <0.
If it is not dak, its default value is 1. Also keep in mind that::is what
the same as: and means to select all indices along this axis.

If the beginning or end of the indexing is not indicated, it will be set by default.
nothing at the beginning / end of the matrix.

myarray[1:5]
array([ 1, 4, 9, 16])

To count from right to left, negative numbers are used.


myarray[-4:]
array([ 81, 100, 121, 144])

myarray[-5::-2]
array([64, 36, 16, 4, 0])

Yessenia Portal Machuca 80 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Ejemplo [Link] tiene la siguiente matriz r.


r = [Link](36)
[Link]((6, 6))

array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17]
[18,19,20,21,22,23]
[24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35]])

The indexing syntax with brackets and commas is: array_name[row, column].
[2, 2]
14

We use the combination of a comma and a colon to select a range of rows


or columns.
r[3, 3:6]

array([21, 22, 23])

r[:2, :-1]
array([[ 0, 1, 2, 3, 4],
[ 6, 7, 8, 9, 10]])

We can also perform conditional indexing. For example, selecting the


values of the matrix r that are greater than 30.
r[r > 30]
array([31, 32, 33, 34, 35])

12.7.2. Advanced Indexing.


This indexing is activated when the selection object is a selection object.
There are two types of advanced indexing: integer and boolean.

Array indexing allows for the selection of arbitrary elements in the


array based on its index. From each row, one element must be selected, and the
The column index specifies the element to choose for each column.

Example.
t = [Link]([[1,2],[3,4],[5,6]])
x[[0,1,2],[0,1,0]]
array([1,4,5])

Yessenia Portal Machuca 81 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Boolean indexing is used when the object is of the boolean type, the result is
returned by the comparison operators.

Example.
x = [Link]([1., -1., -2., 3])
x[x < 0] += 20
x

[1.0, 19.0, 18.0, 3.0]

12.8. Structured sets


Structured arrays help us create an array with a structure like
element.

The following code shows an example of creating a structured array.


import numpy as np

name=[’Harsh’,’Naved’,’Aman’,’Lovish’]
age=[100,70,24,18]
salary=[75500.00,65500.00,55500.00,45500.00]

data=[Link](4,dtype={’names’:(’name’,’age’,’salary’),
’formats’:(’U10’,’i4’,’f8’)})

data[’name’]=name
data[’age’]=age
data[’salary’]=salary

print(data)

#Output

[(’Harsh’, 100, 75500.0) (’Naved’, 70, 65500.0) (’Aman’, 24,


55500.0
(’Lovish’, 18, 45500.0)]

Yessenia Portal Machuca 82 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Once a structured array has been created, data can be accessed from it.
the usual way. For example, to show the value of a particular attribute,
we can simply mention the name of the attribute in single quotes inside
from the brackets.
data[’name’]

#Output
data[’name’]
array([’Harsh’,’Naved’,’Aman’,’Lovish’], dtype=’<U10’)

data[’age’]
array([100, 70, 24, 18])

data[’salary’]
array([ 75500., 65500., 55500., 45500.])

data[1]
(’Naved’, 70, 65500.0)

The Numpy package helps the programmer to handle multidimensional arrays.


in the most sophisticated way.

Yessenia Portal Machuca 83 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

13. Pandas
13.1. What is Pandas?
Pandas is a package that provides a comprehensive set of structures of
data for exploring, cleaning and manipulating data, as well as performing various analyses
statistical and financial.

Some of the tasks that can be


The following are to be carried out:

∗ Reading/writing of many
different data formats.
∗ Selection of subsets of
data.
∗ Calculation between rows and columns.
∗ Application of operations to
independent data groups.
∗ Data transformation.
∗ Combination of several sets
data cough.
∗ Advanced functionality of se-
time beams.
∗ Visualization through mat-
plotlib and seaborn.

To use the functions of Pandas, it is required to import the package in your environment.
IPython:
import pandas as pd
import numpy as np

The two main data structures in Pandas are: Series and DataFrame.

13.2. Series
Series is the main component of Pandas and represents a labeled array.
unidimensional based on [Link] expands the functionality
delndarrayNumPy adding a set of associated labels that are used
to index the elements of the array.

This labeling adds significant power to access the elements of


Series on a NumPy array. Instead of simply accessing the elements
by position, a Series object allows access to the items through the labels
associated index piles. The index also helps in a Pandas feature
called alignment, where operations between two Series are applied to
values with identical labels.

Yessenia Portal Machuca 84 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

13.2.1. Creation and Indexing of Series


You can create a Series object by declaring a scalar value, a NumPy array or
a Python dictionary/list to the function [Link]().

For example, the following command creates a Series object of 100 random numbers.
normally distributed.
In [1]:
[Link](1)
s = [Link]([Link](100))
s

Out[1]:
0 1.624345
1 -0.611756
2 -0.528172
3 -1.072969
...
96 -0.343854
97 0.043597
98 -0.620001
99 0.698032
Length: 100, dtype: float64

Individual elements of a Series can be extracted using the operator []


from the objectSeries. For example, extract the element with the index label 2.
In [2]:
s[2]

Out[2]:
-0.528171752263

Multiple values can be retrieved using a label value array as


is shown below:
In [3]:
s[[2, 5, 20]]

Out[3]:
2 -0.528172
5 -2.301539
20 -1.100619
dtype: float64

Yessenia Portal Machuca 85 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

It supports slicing using slice notation.


The following command retrieves the series elements where the labels are
greater than 3 but less than 8.
In [4]:
s[3:8]
Out[4]:
3 -1.072969
4 0.865408
5 -2.301539
6 1.744812
7 -0.761207
dtype: float64

Note that slicing returns not only the values but also each element.
index (index label and value) of the series with the specified labels.

The head() and tail() functions are provided by Pandas to examine


only the first or last records of a series. By default, they return the first ones.
or the last five rows, respectively, but can use the parameter
simply write an integer to specify the number of rows:
In [5]:
[Link]()
0 1.624345
1 -0.611756
2 -0.528172
3 -1.072969
4 0.865408
dtype: float64

In [7]:
[Link]()
Out[5]:
95 0.077340
96 -0.343854
97 0.043597
98 -0.620001
99 0.698032
dtype: float64

Yessenia Portal Machuca 86 yportal@[Link]


PROGRAMMING IN PYTHON
Nivel Básico

A series consists of an index and a sequence of values. The index can be


recover using the [Link]:
In [6]:
[Link]
Out[6]:
Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46,
47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62,
63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
95, 96, 97, 98, 99], dtype=’int64’)

When a Series object is created and values are not explicitly set
from the index label using the [Link] function, Pandas will assign va-
whole sequential lores starting from 0. To specify index labels not
defaults, use the index argument of the function or assign them using
the [Link] after creating the series.
In [7]:
s2 = [Link]([1, 2, 3, 4], index=[’a’,’b’,’c’,’d’])
s2

Out[7]:
a 1
b 2
c 3
d 4 dtype: int64

A Series can be created directly from a Python dictionary. The keys


from the dictionary are used as index labels for Series:
In [8]:
s2 = [Link]({’a’: 1,’b’: 2,’c’: 3,’d’: 4,’e’: 5})
s2

Out[8]:
a 1
b 2
c 3
d 4
e 5
dtype: int64

Yessenia Portal Machuca 87 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

[Link], shape, and count of values


The number of elements in a Series object can also be determined.
given the function len():
In [9]:
s = [Link]([10, 0, 1, 1, 2, 3, 4, 5, 6, [Link]])
len(s)

Out[9]:
10

The number of elements in a series can also be determined using the


[Link], which returns a tuple that contains the dimensionality of the
series. Since a Series object is one-dimensional, only the value is provided.
of length in the tuple:
In [10]:
[Link]
Out[10]:
(10,)

The number of rows of an object Series that do not have a NaN value can be
determine with the function .count(). The function [Link] creates a NaN value.
In [11]:
[Link]()

Out[11]:
9

To determine all the unique values of a Series, Pandas provides the


[Link]():
In [12]:
[Link]()
Out[12]:
array([5., 0., 1., 2., 3., 4., 5., 6., nan])
dtype: int64

The count of each of the unique elements of a Series object can be


obtain using .value_counts().
In [13]:
s.value_counts()
Out[13]:
5 2
1 2
6 1
4 1
3 1
2 1
0 1
dtype: int64

Yessenia Portal Machuca 88 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

13.2.3. Alignment by index labels


The process of adding two Series objects differs from an array since it first aligns
the data based on the index label values instead of simply
apply the operation to elements in the same position. This becomes significant
equally powerful when using Pandas Series to combine data based
in tags instead of having to manually request the data first.

The result obtained in Series is very different from what would be obtained if
I would add a pure NumPy ndarray. NumPy would add the elements in
identical positions of each array.

For example, there are two objectsSeries:


In [14]:
s3 = [Link]([1, 2, 3, 4], index=[’a’,’b’,’c’,’d’])
s3

Out[14]:
a 1
b 2
c 3
d 4
dtype: int64

In [15]:
s4 = [Link]([4, 3, 2, 1], index=['d', 'c', 'b', 'a'])
s4

Out[15]:
d 4
c 3
b 2
a 1
dtype: int64

The result of adding the two series is shown below:


In [15]:
s3 + s4

Out[15]:
a 2
b 4
c 6
d 8
dtype: int64

Yessenia Portal Machuca 89 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

13.3. The DataFrame


Series is the basis for the representation and manipulation of data in Pandas,
but it can only associate a single value with any index label
dad, ends up having a limited capacity to model multiple variables
of data in each index label.

The Pandas DataFrame solves this problem by providing the ability to


manage multiple series without issues, where each of the series
represents a column of the DataFrame and also automatically aligns the
values of each column along the index labels of the DataFrame.

In a way, a DataFrame can be considered as a dictionary.


Inside one or more objectsSeries, like a relational database table.
A good way to think about a DataFrame is that it unifies two or more series into
a single data structure.

A DataFrame has two axes, horizontal and vertical. The functions of Pandas are
they can be applied to either of the two axes, essentially indicating that it applies
to all the values of the selected rows or to all the items of the columns
specified.

13.3.1. Creation of a DataFrame


Hay varias maneras de crear unDataFrame. Probablemente, el más sencillo es
create it from a NumPy array, with the DataFrame() function.
In [16]:
[Link]([Link]([[10, 11], [20, 21]]))

Out[16]:
0 1
0 10 11
1 20 21

Each row of the array forms a row in the DataFrame. Since we did not specify a
index, Pandas creates a default int64 index in the same way as a
Series. Since we also do not specify the column names, Pandas also
assign the names for each column with a zero-based integer series.

A DataFrame can also be initialized from a list of Series objects:


In [17]:
df1 = [Link]([[Link]([Link](10, 15)),
[Link]([Link](15, 20))
df1

Out[17]:
0 1 2 3 4
0 10 11 12 13 14
1 15 16 17 18 19

Yessenia Portal Machuca 90 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

The dimensions of a DataFrame can be determined using its property


.shape. UnDataFrames are always bidimensional. The shape informs us with the
the first value is the number of rows and the second is the number of columns:
In [18]:
[Link]
Out[18]:
(2, 5)

Column names can be specified at the time of creating the


DataFrame using the argument columns of the DataFrame() function.
example:
In [19]:
df = [Link]([Link]([[10, 11], [20, 21]]),
columns=[’a’,’b’])
df

Out[19]:
a b
0 10 11
1 20 21

Likewise, you can access or change the names of the columns of a DataFrame.
with the [Link]. For example:
In [20]:
[Link]

Out[20]:
Index([u’a’,u’b’], dtype=’object’)

In [21]:
[Link] = ['c1', 'c2']
df
Out[26]:
c1 c2
0 10 11
1 20 21

Index labels can also be assigned using the index argument.


from the function DataFrame() or assigning a list directly to the property
.index:
In [22]:
df = [Link]([Link]([[0, 1], [2, 3]]),
columns=[’c1’,’c2’],
index=[’r1’,’r2’])
df

Out[22]:
c1 c2
r1 0 1
r2 2 3

Yessenia Portal Machuca 91 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

You can also create a DataFrame by declaring a dictionary that contains


one or more objectsSeries, where the dictionary keys contain the names
from the columns and each series is a column of data:
In [23]:
s1 = [Link]([Link](1, 6, 1))
s2 = [Link]([Link](6, 11, 1))
[Link]({’c1’: s1,’c2’: s2})

Out[23]:
c1 c2
0 1 6
1 2 7
2 3 8
3 4 9
4 5 10

UnDataFrame also performs automatic data alignment for


The indicated series by a dictionary. As a demonstration, the following command-
Add a third column when creating the DataFrame. This third object
Series contains two values and will specify its index. When the DataFrame is created,
All the series in the dictionary align with each other using the index label a
measure that is added to the DataFrame:

In [24]:
s3 = [Link]([Link](12, 14), index=[1, 2])
[Link]({’c1’: s1,’c2’: s2,’c3’: s3})
Out[24]:
c1 c2 c3
0 1 6 NaN
1 2 7 12
2 3 8 13
3 4 9 NaN
4 5 10 NaN

In the previous example, it can be seen that the first two Series objects did not have a
index specified by which both were indexed with 0 to 4. The third series
it has index values; therefore, the values for those indexes are placed in
The DataFrame is in the row with the corresponding index of the previous columns.
Then, Pandas automatically fills with NaN for the values that do not
were supplied.

Another way to create a DataFrame is to import data from a csv file. Excel, for
the function read_csv() or read_excel() is used respectively. For ex-
import external files in other formats check the link[Link]
docs/stable/reference/[Link].

Yessenia Portal Machuca 92 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

For example, create a DataFrame from a .csv file


In [25]:
sp500 = pd.read_csv("[Link]",
index_col='Symbol'
usecols=[0, 2, 3, 7]

Out[25]:
Sector Price Book Value
Symbol
MMM Industrials 141.14 26.668
ABT Health Care 39.60 15.573
ABBV Health Care 53.95 2.954
ACN Information Technology 79.79 8.326
ACE Financials 102.91 86.897

13.3.2. Column selection from a DataFrame


To select columns from a DataFrame, the [] operator is used, and the index must be specified.
of the columns to select separated by commas.
For example, considering the DataFrame of the S&P 500, we obtain the first 3 rows of
column 1 and 2.
In [26]:
sp500[[1, 2]].head(3)

Out[26]:
Price Book Value
Symbol
MMM 141.14 26.668
ABT 39.60 15.573
ABBV 53.95 2.954

You can also select multiple columns by the name of the columns.
For example:
In [27]:
sp500[[’Price’,’Sector’]]

Out[27]:
Price Sector
Symbol
MMM 141.14 Industrials
ABT 39.60 Health Care
ABBV 53.95 Health Care
ACN 79.79 Information Technology
... ... ...
YUM 74.77 Consumer Discretionary
ZMH 101.84 Health Care
ZION 28.43 Financials
ZTS 30.53 Health Care
[500 rows x 2 columns]

Yessenia Portal Machuca 93 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Finally, the columns can also be extracted using what is known


as attribute access. Each column in a DataFrame adds dynamically-
lie a property to the DataFrame for each column where the name of the
property is the name of the column. That is, when selecting a single column,
the resulting value is a Series object. For example:
In [28]:
[Link]

Out[28]:
Symbol
MMM 141.14
ABT 39.60
ABBV 53.95
ACN 79.79
...
YUM 74.77
ZMH 101.84
ZION 28.43
ZTS 30.53
Name: Price, dtype: float64

13.3.3. Selecting rows from a DataFrame using the index


The selection of rows using indexing in a DataFrame breaks down as follows
general categories of operations:
Indexing with the operator [].
Label or location-based search using .loc, .iloc, .ix
Scalar search by label or location using .[Link]

Slicing with the [] operator


Slicing a DataFrame through its index is identical to slicing a Series.
Slicing is done both with positions and with labels.

Examples:

In [29]:
sp500[:3]
Out[29]:
Sector Price Book Value
Symbol
MMM Industrials 141.14 26.668
ABT Health Care 39.60 15.573
ABBV Health Care 53.95 2.954

Yessenia Portal Machuca 94 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

In [30]:
sp500[’XYL’:’YUM’]
Out[30]:
Sector Price Book Value
Symbol
XYL Industrials 38.42 12.127
YHOO Information Technology 35.02 12.768
YUM Consumer Discretionary 74.77 5.147

2. Selection of rows by index label or location

Rows can be extracted using .loc[], specifying the label value.


of the index. For example:
In [31]:
[Link][['MMM','MSFT']]

Out[31]:
Sector Price Book Value
Symbol
MMM Industrials 141.14 26.668
MSFT Information Technology 40.12 10.584

Rows can also be extracted by indicating the index location using


.iloc[]:
In [32]:
[Link][[0, 2]]

Out[32]:
Sector Price Book Value
Symbol
MMM Industrials 141.14 26.668
ABBV Health Care 53.95 2.954

It is possible to search for the index location of a specific label value.


what can be used to recover the row(s):
In [33]:
i1 = [Link].get_loc('MMM')
i2 = [Link].get_loc('A')
i1, i2

Out[33]:
(0, 10)

In [34]:
[Link][[i1, i2]]
Out[34]:
Sector Price Book Value
Symbol
MMM Industrials 141.14 26.668
A Health Care 56.18 16.928

Yessenia Portal Machuca 95 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

3. Selection of rows by index label and/or location

An UnDataFrame also contains a property .ix[] that can be used


to search for rows either by the index label or by the location, essential-
mind [Link] a.
For example:
In [35]:
[Link][['MSFT','ZTS']]

Out[35]:
Sector Price Book Value
Symbol
MSFT Information Technology 40.12 10.584
ZTS Health Care 30.53 2.150

Location-based search can be performed with the following code.


In [36]:
[Link][[10, 200, 450]]

Out[36]:
Sector Price Book Value
Symbol
A Health Care 56.18 16.928
GIS Consumer Staples 53.81 10.236
TRV Financials 92.86 73.056

4. Scalar search by label or location

Scalar values can be searched by label using .at[] indicating


the row label and then the column name/value:
In [37]:
[Link]['MMM','Price']

Out[37]:
141.14

Scalar values can also be searched by location using


.iat[] indicating the location of the row as well as the column. This is the
preferred method for accessing individual values and results.
In [38]:
[Link][0, 1]

Out[38]:
141.14

Yessenia Portal Machuca 96 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

13.3.4. Line selection using Boolean selection


Rows can also be selected using Boolean indexing with an array.
calculated from the result of applying a logical condition to the values of
any of the columns. This allows us to create more complex selections
that are simply based on index tags or positions.

For example, select all companies that have a price below


100.0
In [39]:
[Link] < 100

Out[39]:
Symbol
MMM False
ABT True
ABBV True
ACN True
...
YUM True
ZMH False
ZION True
ZTS True
Name: Price, Length: 500, dtype:bool

This yields a Series that can be used to select rows where the value
esTrue:
In [40]:
sp500[[Link] < 100]

Out[40]:
Sector Price Book Value
Symbol
ABT Health Care 39.60 15.573
ABBV Health Care 53.95 2.954
ACN Information Technology 79.79 8.326
ADBE Information Technology 64.30 13.262
... ... ... ...
YHOO Information Technology 35.02 12.768
YUM Consumer Discretionary 74.77 5.147
ZION Financials 28.43 30.191
ZTS Health Care 30.53 2.150

[407 rows x 3 columns]

Yessenia Portal Machuca 97 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Multiple conditions can be combined using parentheses and at the same time ...
select only a subset of the columns. The following command retrieves the
symbols and the price of all stocks with a price below 10 and above
0:

In [41]:
sp500[([Link] < 10) & ([Link] > 0)] [[‘Price’]]

Out[41]:
Symbol Price
FTR 5.81
HCBK 9.80
HBAN 9.10
Hello 8.82
WIN 9.38

13.3.5. Arithmetic in a DataFrame


The arithmetic operations that use scalar values will be applied to each element.
mention of a DataFrame.

By default, any arithmetic operation will be applied to all rows and columns.
from a DataFrame and will return a new DataFrame with the results (leaving the
original without changes).

When performing an operation between a DataFrame and a Series, Pandas will align the
index of Series along the columns of the DataFrame, which is called
transmission in line.

For example:
In [42]:
[Link](123456)
df = [Link]([Link](5, 4),
columns=[’A’,’B’,’C’,’D’])

In [42]:
df - [Link][0]

An arithmetic operation between two DataFrame objects will align with the labels.
stack of columns and indices.

Yessenia Portal Machuca 98 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

For example: extract a small portion from a DataFrame and subtract from a DataFrame.
The result shows that the aligned values are subtracted from a0, while the
others adjust to NaN:
In [43]:
subframe = df[1:4][[’B’,’C’]]
subframe

Out[43]:
B C
1 -0.173215 0.119209
2 -2.104569 -0.494929
1 -0.706771 -1.039575

In [44]:
df subframe
Out[44]:
A B C D
0 NaN NaN NaN NaN
1 NaN 0 0 NaN
2 NaN 0 0 NaN
3 NaN 0 0 NaN
4 NaN NaN NaN NaN

Additional control of an arithmetic operation can be obtained using the


arithmetic methods provided by the DataFrame object. These methods pro-
they provide the specification of a particular shaft. The following command displays the
subtract along the axis of a column using the DataFrame object; the method
Subtract the column from each column:
In [45]:
a_col = df[’A’]
[Link](a_col, axis=0)

13.4. Reindexing of Series and DataFrame objects


Reindexing in Pandas is a process that makes the data of an object
SeriesDataFrame matches a given set of labels across a
specific axis. This is the core of the functionalities of Pandas as it allows
the alignment of labels across multiple objects.

The process of performing a reindexing does the following:

∗ Rearrange the existing data to match a set of labels.


task.
∗ Insert NaN markers where data does not exist for a label.
∗ Fill in the missing data for a label using a type of logic (by
default add NaNs).

Yessenia Portal Machuca 99 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Reindexing an object Series. For example, the following series has an index
con valores numéricos, y el índice es modificado a alfabético mediante una simple
assignment of a list of characters to the [Link], making the
values can be accessed through the character labels in the new
index.
In [46]:
[Link](1)
s = [Link]([Link](5))
s
Out[46]:
0 1.624345
1 -0.611756
2 -0.528172
3 -1.072969
4 0.865408

dtype: float64

In [47]: [Link] = ['a','b','c','d','e']


s

Out[47]:
a 1.624345
-0.611756
c -0.528172
-1.072969
0.865408
dtype: float64

Greater flexibility is provided in the creation of a new index using


the method .reindex(). If there is an index label created for which Series
If it did not have an existing label, it will be assigned the value NaN.

An example of the flexibility of reindex() over direct assignment of the property.


[Link] that the list provided to [Link]() can have a length
different from the number of rows in Series:
In [48]:
s2 = [Link](['a', 'c', 'e', 'g'])
s2[’a’] = 0
s2

Out[48]:
a 0.000000
c -0.528172
e 0.865408
g NaN
dtype: float64

Yessenia Portal Machuca 100 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Reindexing is also useful when you want to align two series to perform a
matching operation between the elements of each series, but for some reason
The reason is that both series had index labels that did not align initially.

For example, the first objectSeries has indices like sequential integers.
but the second has a string representation of what would be numbers
sequential integers. The addition of both Series has the following result,
where everyone is NaNs and there are repeated label values:
In [49]:
s1 = [Link]([0, 1, 2], index=[0, 1, 2])
s2 = [Link]([3, 4, 5], index=[’0’,’1’,’2’])
s1 + s2

Out[49]:
0 NaN
1 NaN
2 NaN
0 NaN
1 NaN
2 NaN
dtype: float64

In this case, Pandas first try to align with the indices and when they do not find
matches, copy the index labels of the first object Series they attempt
add the indices of the second objectSeries. But since they are of another type, they
it resets to a zero-based whole sequence, which gives
como resultado valores duplicados. Y finalmente, todos los valores resultantes son
NaN because the operation tries to add the item from the first series with the label
enter 0, which has the value 0 but cannot find the item from the other series
with the whole label 0; therefore, the result is NaN. This inconvenience is
solve with the reindexing of the second series, converting the values to aint:
In [50]:
[Link] = [Link](int)
s1 + s2

Out[50]:
0 3
1 5
2 7
dtype: int64

The default action of inserting NaN as a missed value during .reindex()


it can be changed using the argument fill_value, which fills with zeros
instead of NaN:

Yessenia Portal Machuca 101 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

In [52]:
s2 = [Link]()
[Link](['a', 'f'], fill_value=0)

Out[51]:
a 1.624345
f 0.000000
dtype: float64

When a reindex is performed on ordered data, such as a time series, it is


it is possible to perform interpolation or filling of values. To demonstrate the concept,
let's use the following objectSeries:
In [52]:
s3 = [Link](['red', 'green', 'blue'], index=[0, 3, 5])
s3

Out[52]:
0 red
3 green
5 blue
dtype:object

The following code shows forward filling, which is often used to


it refers to the last known value. The objectSeries is reindexed
to create a contiguous integer index using the parameter method='ffill',
any new index label is assigned a previously seen value
length of Series.
In [53]:
[Link]([Link](0,7), method='ffill')

Out[53]:
0 red
1 red
2 red
3 green
4 green
5 blue
6 blue
dtype:object

On the contrary, when sealing backwards it is used by utilizing the parameter


method='bfill'.
In [54]:
[Link]([Link](0,7), method='bfill')

Out[54]:
0 red
1 green
2 green
3 green 4 blue 5 blue 6 NaN dtype:object

Yessenia Portal Machuca 102 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

13.5. DataFrame Manipulation Applied to Finance.


Before starting to explore the functions to manipulate DataFrame, we will import
some previous packages.
import Pandas as pd
import numpy as np
importdatetime
import [Link] as plt

Configure matplotlib package


%matplotlib inline
pd.set_option('display.notebook_repr_html', False)
pd.set_option('display.max_columns', 15)
pd.set_option('display.max_rows', 8)
pd.set_option('precision', 3)

We imported stock information for MSFT and AAPL from the year 2019 extracted from
Yahoo! Finance, to exemplify the concepts that will be explored in this section
from Pandas.

The following command can be used to load daily stock information.


directly from the Web:
import [Link] as web
start = [Link](2019, 1, 1)
end = [Link](2019, 12, 30)
msft = [Link]("MSFT", 'yahoo', start, end)
aapl = [Link]('AAPL', 'yahoo', start, end)

Save the information in csv files.


# msft.to_csv("[Link]")
# aapl.to_csv("[Link]")

Remember that to import data from csv files, we use the function pd.read_csv().
And part of the data from the DataFrame is extracted for the purposes of the examples.

In [1]:
msft = pd.read_csv("[Link]", index_col=0, parse_dates=True)
aapl = pd.read_csv("[Link]", index_col=0, parse_dates=True)

In [2]:
msft[:3]

In [3]:
aapl[:3]

Yessenia Portal Machuca 103 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

13.5.1. Reorganization and restructuring of data


When working with financial information, it often happens that the data
recovered from almost any data source will not be in the format that
needed to carry out the desired analyses. Or perhaps, equally likely, the
data from a specific source may be incomplete and require collection
from another source, at which point, the data must be concatenated or
merged through joint operations between the data.

Even if the data is complete or after combining it from various sources,


they can be organized in a way that does not lead to a specific type of
analysis. Therefore, it is necessary to restructure it.

Pandas offers a wide variety of functions for concatenating, merging and reshaping.
stop the data. The following sections take us through various scenarios
common to each one, using stock data (examples: MSFT and AAPL).

[Link] of multiple DataFrame objects

Concatenation in Pandas is the process of creating a new Pandas object.


combining data from two (or more) Pandas objects into a new Pandas object
along a single specified axis of the two objects. The concatenation
With stock data, it is useful to combine values taken from different ones.
time periods, to create additional columns that represent others
measurements at a specific date and time for a specific action,
or to add a column for the same measurement of a different action
but for the same period of time.
Pandas concatenates DataFrame objects along an axis.
specific: the two axes are the index labels of the rows and the columns.
This is done first by extracting the labels from the two object indices
DataFrame along the specified axis, using that set as index
of the new DataFrame, and then copying the values along the other axis in
the result in an orderly manner, that is, from the first DataFrame and
then from the secondDataFrame.
The result of a concatenation always contains the union of the number of
elements in both objects along the specific axis. This is different
from a fusion or union that could result in the resulting number of
items may not necessarily be equivalent to the union of the number of items in
the objectsDataFrame from origin.
The difficult part of concatenation is how Pandas deal with objects
along the other axis during the concatenation. The set of values, already
they are files when concatenating along the columns or columns when concatenating
along rows, it is defined using relational algebra on the values of the index
of that axis.

Yessenia Portal Machuca 104 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

For example:
In [4]:
msftA01 = msft[’2019-01’][[’Adj Close’]]
msftA02 = msft[’2019-02’][[’Adj Close’]]
msftA01[:3]

Out[4]:

Date Adj Close


January 3, 2019, 24.42
2019-01-04 25.00
2019-01-05 25.25

In [5]:
msftA02[:3]

Out[5]:
Date Adj Close
2019-02-01 27.27
2019-02-02 27.32
2019-02-03 27.59

To combine both datasets into a single DataFrame, it is done


a concatenation, using the function .concat().
In [6]:
[Link]([[Link](3), [Link](3)])

Out[6]:

Date Adj Close


2019-01-03 24.42
2019-01-04 25.00
2019-01-05 25.25
February 1, 2019 27.27
2019-02-02 27.32
2019-02-03 27.59

The following example concatenates the first five adjusted closing values.
in January for both MSFT and AAPL. These have index labels
identical and result in duplicate index labels in the new
DataFrame. During a concatenation along the row axis, Pandas
the index labels will not be aligned. They will be copied and this may create labels
of duplicate and identical indices:

Yessenia Portal Machuca 105 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

In [7]:
aaplA01 = aapl[’2019-01’][[’Adj Close’]]
withDups = [Link]([msftA01[:3], aaplA01[:3])
withDups

Out[7]:

Date Adj Close


2019-01-03 24.42
2019-01-04 25.00
2019-01-05 25.25
2019-01-03 55.41
2019-01-04 55.71
2019-01-05 56.33

The argument keys of the .concat() function is used to add to a


additional level to the index (creating a MultiIndex), which can then be used
to identify the source DataFrame. For example:
In [8]:
closes = [Link]([msftA01[:3], aaplA01[:3]],keys=[’MSFT’,’AAPL’])
closes

Out[8]:
Date Adj Close
MSFT 2019-01-03 24.42
2019-01-04 25.00
2019-01-05 25.25
AAPL 2019-01-03 55.41
2019-01-04 55.71
2019-01-05 56.33

Using this new MultiIndex, it is possible to extract the values of any


of the actions of this newDataFrame using only the labels
of index. For example:
In [9]:
[Link]['MSFT'][:3]

Out[9]:

Date Adj Close


2019-01-03 24.42
2019-01-04 25.00
2019-01-05 25.25

The concatenation along the axis of the row can also be carried out.
using DataFrame objects with multiple columns. Likewise if
the argument key is not used, there will be duplicate rows.

Yessenia Portal Machuca 106 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

In [10]:
msftAV = msft[[’Adj Close’,’Volume’]]
aaplAV = msft[['Adj Close', 'Volume']]
[Link]([msftAV, aaplAV])

Out[10]:

Date Adj Close Volume


2019-01-03 24.42 64731500
2019-01-04 25.00 80516100
2019-01-05 25.25 56081400
2019-01-06 25.64 99455500
... ... ...
2019-12-24 70.72 43938300
2019-12-26 69.74 75609100
2019-12-27 70.02 113780100
2019-12-28 69.28 88569600
[498 rows x 2 columns]

The objects of a concatenation DataFrame can have different columns.


us. For example:
In [11]:
aaplA = aapl[['Adj Close']]
[Link]([msftAV, aaplA])

Out[11]:
Date Adj Close Volume
2019-01-03 24.42 64731500
2019-01-04 25.00 80516100
2019-01-05 25.25 56081400
2019-01-06 25.64 99455500
... ... ...
2019-12-24 70.72 NaN
2019-12-26 69.74 NaN
2019-12-27 70.02 NaN
2019-12-28 69.28 NaN
[498 rows x 2 columns]

Since the rows that originate from the DataFrame aaplAno have the
Volume column, the Pandas insert NaN in the Volume column for
those rows.
The set of columns that results from a concatenation along the axis
from the row is the result of relational algebra through the names of the
columns. In this default scenario, the resulting column is the union
of the column names of each DataFrame. This can be changed.
to an intersection using the dejoin parameter. For example:

Yessenia Portal Machuca 107 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

In [12]:
[Link]([msftAV, aaplA], join=’inner’)

Out[12]:
Date Adj Close
2019-01-03 24.42
2019-01-04 25.00
2019-01-05 25.25
2019-01-06 25.64
... ...
2019-12-24 70.72
2019-12-26 69.74
2019-12-27 70.02
2019-12-28 69.28
[498 rows x 1 columns]

To concatenate columns, you can specify the axis, they use-


doaxis=1.
In [13]:
msftA = msft[[’Adj Close’]]
closes = [Link]([msftA, aaplA], axis=1)
closes[:3]

Out[13]:

Date Adj Close Adj Close


2019-01-03 24.42 55.41
2019-01-04 25.00 55.71
2019-01-05 25.25 56.33

It is also possible to concatenate with multiple columns where the objects


DataFrames do not have the same set of index labels. For example:
In [14]:
[Link]([msftAV[:5], aaplAV[:3]], axis=1, keys=['MSFT', 'AAPL'])

Out[14]:
MSFT AAPL
Date Adj Close Volume Adj Close Volume
2019-01-03 24.42 64731500 55.41 75555200
2019-01-04 25.00 80516100 55.71 65005500
January 5, 2019 25.25 56081400 56.33 67817400
2019-01-06 25.64 99455500 NaN NaN
2019-01-09 25.31 59706800 NaN NaN

This results in duplicate column names, so it is used


the parameter keys to create MultiIndex for the columns. When you have
row index labels not found in, Pandas fills the rows
conNaN.

Yessenia Portal Machuca 108 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Just like with concatenation along the row axis, the type of
union made by [Link]() can be changed using the parameter
dejoin. The following command performs an inner join instead of a
external, which results in the intersection of the row index labels:
In [15]:
[Link]([msftA[:5], aaplA[:3]], axis=1,
join=’inner’, keys=[’MSFT’,’AAPL’])

Out[15]:
Date Adj Close Adj Close
2019-01-03 24.42 55.41
2019-01-04 25.00 55.71
2019-01-05 25.25 56.33

The resulting DataFrame only has three rows because of those index labels.
they were the only common ones in the two concatenated DataFrame objects.
If you want to ignore indices in the result of [Link](), you can use the
parameter ignore_index=True, which will not consider the index and will create a
zero-based integer index by default, as shown here:
In [16]:
[Link]([msftA[:3], aaplA[:3]], ignore_index=True)

Out[16]:
Adj Close
0 24.42
1 25.00
2 25.25
3 55.41
4 55.71
5 56.33

Yessenia Portal Machuca 109 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

2. DataFrame object fusion

The combination of Pandas objects is allowed through operations of


union of relational database, through the function [Link]().
The merging in Pandas differs from concatenation because the function [Link]()
combine data based on the values of the data in one or more co-
columns instead of using the index label values along a
specific axis.
The default process that [Link]() uses is to first identify the co-
columns whose data will be used in the merge, and then perform a join
internal based on that information. The columns used in the splice are
they are selected by default, as those of both DataFrame objects with names
common.
For example:
In [17]:
msftAR = msftA.reset_index()
msftVR = msft[['Volume']].reset_index()
msftAR[:3]

Out[17]:
Date Adjusted Close
0 2019-01-03 24.42
1 2019-01-04 25.00
2 2019-01-05 25.25

In [18]: msftVR[:3]

Out[18]:
Date Volume
0 2019-01-03 64731500
1 2019-01-04 80516100
2 2019-01-05 56081400

Instead of using Date as an index, they have Date as a column to


that can be used in the fusion. Our goal is to create a DataFrame
that contains a Date column and the AdjClose and Volume columns. This is
it can be achieved with the following code.
In [19]:
msftCVR = [Link](msftAR, msftVR)
msftCVR[:5]

Out[19]:
Date Adj Close Volume
0 2019-01-03 24.42 64731500
1 2019-01-04 25.00 80516100
2 2019-01-05 25.25 56081400
3 2019-01-06 25.64 99455500
4 2019-01-09 25.31 59706800

Yessenia Portal Machuca 110 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

The common column is Date; therefore, Pandas performs a join.


internal about the values of that column in both DataFrame objects. A
Once that set is calculated, Pandas copies into the appropriate values for each
file of both objects DataFrame.
The types of joins supported by [Link]() are similar to the different
types of joins supported in relational databases. These are: left,
right, outereinner.
The following DataFrame will be used for the examples.
In [20]:
msftAR0_5 = msftAR[0:5]
msftAR0_5

Out[20]:
Date Adj Close
0 2019-01-03 24.42
1 2019-01-04 25.00
2 2019-01-05 25.25
3 2019-01-06 25.64
2019-01-09 25.31

In [21]:
msftVR2_4 = msftVR[2:4]
msftVR2_4

Out[21]:
Date Volume
2 2019-01-05 56081400
3 2019-01-06 99455500

Internal union (inner): since there are only two rows with matching dates,
the result only has two rows and merges the objectsDataFrame where the
Date values are common.
In [22]:
[Link](msftAR0_5, msftVR2_4)

Out[22]:
Date Adj Close Volume
0 2019-01-05 25.25 56081400
1 2019-01-06 25.64 99455500

Yessenia Portal Machuca 111 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

This can be changed for an external join with how='outer'. It returns-


See all the rows of the external DataFrame (msftAR0_5), and the values that
they are not found in the internal DataFrame (msftVR2_4) they are replaced with
NaN
In [23]:
[Link](msftAR0_5, msftVR2_4, how='outer')

Out[23]:
Date Adj Close Volume
0 2019-01-03 24.42 NaN
1 2019-01-04 25.00 NaN
2 2019-01-05 25.25 56081400
3 2019-01-06 25.64 99455500
4 2019-01-09 25.31 NaN

[Link]
Financial data is often stored in a format where the
data are not normalized and, therefore, have repeated values in mu-
columns or values that logically should exist in other tables. A
an example of this would be the following, where the historical prices for multi-
multiple actions are represented in a single DataFrame using a column
Symbol. The following code creates this schema.
In [24]:
[Link](0,'Symbol','MSFT')
[Link](0, 'Symbol', 'AAPL')
combined = [Link]([msft, aapl]).sort_index()
s4p = combined.reset_index();
s4p[:5]

Out[24]:
Date Symbol Open High Low Close Volume Adj Close
0 2019-01-03 MSFT 26.55 26.96 26.39 26.77 64731500 24.42
1 2019-01-03 AAPL 409.40 412.50 409.00 411.23 75555200 55.41
2 2019-01-04 MSFT 26.82 27.47 26.78 27.40 80516100 25.00
3 2019-01-04 AAPL 410.00 414.68 409.28 413.44 65005500 55.71
4 2019-01-05 MSFT 27.38 27.73 27.29 27.68 56081400 25.25

Si se requiere extraer un nuevoDataFrameindexado por fecha y con columnas


that represent the value of AdjClose for all listed values in the
column Symbol. This can be done using the [Link]().
In [25]:
closes = [Link](index='Date', columns='Symbol',
values=’Adj Close’)
closes[:3]

Out[25]:
Date AAPL MSFT
2019-01-03 55.41 24.42
2019-01-04 55.71 25.00
2019-01-05 56.33 25.25

Yessenia Portal Machuca 112 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

This function takes all distinct values from the Symbol column, the
rotate into columns in the new DataFrame, and then include the values in those
columns from the AdjClose value for the specific symbol of the DataFrame
original.
4. Stacking (stack) and unstacking (unstack)

Functions similar in operation to the pivot function are .stack()


[Link]().
The function .stack() moves the column labels to another level of the
index. For example:
In [26]:
stackedCloses = [Link]()
stackedCloses

Out[26]:
Date Symbol
2019-01-03 AAPL 55.41
MSFT 24.42
2019-01-04 AAPL 55.71
MSFT 25.00
...
2019-12-27 AAPL 70.02
MSFT 25.29
2019-12-28 AAPL 69.28
MSFT 24.91
dtype: float64

This has created a new index with an additional level called Symbol. Each
the file is then indexed by Date and Symbol, and for each unique level of
Date and Symbol, Pandas has inserted the appropriate AdjClose value.
The result of this allows the efficient search for any value of
AdjClose using the index. For example
In [27]:
[Link]['2019-01-03','AAPL']

Out[27]:
55.41

Using a MultiIndex, it is also possible to search for values for a date


specify:
In [28]:
[Link]['2019-01-03']

Out[28]:
Symbol
AAPL 55.41
MSFT 24.42
dtype: float64

Yessenia Portal Machuca 113 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

For a specific symbol, the code is:


In [29]:
[Link][:, 'MSFT']

Out[29]:
Date
2019-01-03 24.42
2019-01-04 25.00
January 5, 2019 25.25
2019-01-06 25.64
...
2019-12-24 25.38
2019-12-26 25.20
2019-12-27 25.29
2019-12-28 24.91
dtype: float64

The function .unstack() performs the opposite function; that is, it pivots a
level of an index in a column of a new DataFrame. The following
command deactivates the last level of the MultiIndex and results in a DataFrame
equivalent to the original.
In [30]:
unstackedCloses = [Link]()
unstackedCloses[:3]

Out[30]:

Date AAPL MSFT


2019-01-03 55.41 24.42
2019-01-04 55.71 25.00
2019-01-05 56.33 25.25

5. Melting

Melting is the process of transforming a DataFrame into a format in which


each row represents a unique combination of dependent variable data.
The following code shows the melting process of the DataFrames4p in a
combinationid-variable that consists of the columns Date and Symbol
as ID and the other columns are assigned to the variable column.
In [31]:
melted = [Link](s4p, id_vars=[’Date’,’Symbol’])
melted[:5]

Out[31]:
Date Symbol variable value
0 2019-01-03 MSFT Open 26.55
1 2019-01-03 AAPL Open 409.40
2 2019-01-04 MSFT Open 26.82
3 2019-01-04 AAPL Open 410.00
4 2019-01-05 MSFT Open 27.38

Yessenia Portal Machuca 114 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

During the melting process, the columns specified by the parameter


id_vars remain as columns (in this case Date and Symbol). All
the other columns have their names assigned to the values of the column
devariable.
This data organization is useful for selecting information based on
a specific ID variable. For example.
In [32]:
melted[([Link]=='2019-01-03') & ([Link]=='MSFT')]

Out[32]:
Date Symbol variable value
0 2019-01-03 MSFT Open 26.55
498 2019-01-03 MSFT High 26.96
996 2019-01-03 MSFT Low 26.39
1494 2019-01-03 MSFT Close 26.77
1992 2019-01-03 MSFT Volume 64731500.00
2490 2019-01-03 MSFT Adj Close 24.42

13.5.2. Grouping and aggregation


Pandas data can be easily divided into groups and then summarized.
using various statistical and quantitative calculations. This process in the nomen-
The terminology of Pandas is often referred to as the combination pattern.
split application.

Divide

Objects in Pandas are divided into groups using the .groupby() method.
We previously reorganized the data from the s4g DataFrame.
In [33]:
s4g = combined[['Symbol', 'AdjClose']].reset_index()
[Link](1, 'Year', [Link](s4g['Date']).year)
[Link](2, 'Month[:5]', [Link](s4g['Date']).month)

s4g[:5]

Out[33]:
Date Year Month Symbol Adj Close
0 2019-01-03 2019 1 MSFT 24.42
1 2019-01-03 2019 1 AAPL 55.41
2 2019-01-04 2019 1 MSFT 25.00
3 2019-01-04 2019 1 AAPL 55.71
4 2019-01-05 2019 1 MSFT 25.25

These data differ from the previous ones, as only the AdjClose value is used.
and the Date column is split into two other columns, Year and Month. This
The division of the date is made to be able to provide the capability to group.
the data by Month and Year for each Symbol variable.

Yessenia Portal Machuca 115 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

These data consist of four categorical variables and one continuous variable.
AdjC Close. In Pandas, it is possible to group by any categorical variable.
indicating your name in the [Link](). For example:
In [34]:
[Link]('Symbol')

Out[34]:
<[Link] object at 0x7ffaeeb49a10>

The result of calling .groupby() on a DataFrame is not the data


current groups but a DataFrame GroupBy object. The grouping still
it has not been carried out, as it is a deferred grouping process in
the Pandas.
This result of .groupby() is a subclass of a GroupBy object and is
a provisional description of the grouping that is going to be carried out. This allows
the Pandas to validate first that the grouping description that
it has provided is valid in relation to the data before it starts
the processing.
There are several useful properties in a GroupBy object. The groups property
it will return a Python dictionary whose keys represent the name of each
group (if multiple columns are specified, it is a tuple), and the values are
a matrix of the index labels contained within each group. For
example:
In [35]:
grouped = [Link]('Symbol')
type([Link])

Out[35]:
dict

In [36]:
[Link]

Out[36]:
{u’AAPL’: [1, 3, 5, 7, 9, 11, 13, 14, 16, 18, 20, 23, 25, 27, 29,
30, 33, 34, 37, 38, 41, 43, 45, 46, 48, 50, 53, 54, 56, 58, 61,
63, 64, 67, 69, 71, 72, 75, 77, 79, 81, 82, 84, 89, 91, 92, 94,
...
452, 455, 456, 458, 460, 463, 464, 466, 468, 471, 472, 474, 476,
478, 480, 482, 484, 487, 488, 490, 492, 494, 497]
’MSFT’: [0, 2, 4, 6, 10, 12, 15, 17, 19, 21, 22, 24, 26, 28, 31, 32,
...
477, 479, 481, 483, 485, 486, 489, 491, 493, 495, 496]}

Yessenia Portal Machuca 116 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

The Python function len() can be used to return the number of groups.
that will result from the grouping. You can also use the property .ngroups:
In [37]:
len(grouped), [Link]

Out[37]:
(2, 2)

The division is not carried out until some type of action is taken on it.
objectGroupBy. However, it is possible to iterate over several properties of the
object to see how the data will be grouped (which forces them to be grouped).
In [38]:
def print_groups(group_object):
forname, groupingroupobject:
print(name)
print([Link]())

In [39]:
print_groups(grouped)

Out[39]:
AAPL
Date Year Month Symbol Adj Close
1 2019-01-03 2019 1 AAPL 55.41
3 2019-01-04 2019 1 AAPL 55.71
5 2019-01-05 2019 1 AAPL 56.33
7 2019-01-06 2019 1 AAPL 56.92
9 2019-01-09 2019 1 AAPL 56.83
MSFT
Date Year Month Symbol Adj Close
0 2019-01-03 2019 1 MSFT 24.42
2 2019-01-04 2019 1 MSFT 25.00
4 2019-01-05 2019 1 MSFT 25.25
6 2019-01-06 2019 1 MSFT 25.64
8 2019-01-09 2019 1 MSFT 25.31
It is possible to create, for each distinct value in the Symbol column of the DataFrame
original, a group that consists of a DataFrame. Then it copies the columns
and the ungrouped data in each of those DataFrame objects and then
use the command of the specified columns as the group name.
The .size() function of the object provides a good summary of the size of all the
groups:
In [40]:
[Link]()

Out[40]:
Symbol
AAPL 249
MSFT 249
dtype: int64

Yessenia Portal Machuca 117 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

If you want the data of the elements of a specific group, you can use
the property.get_group(). For example: retrieve the MSFT group.
In [41]:
grouped.get_group('MSFT')

Out[41]:
Date Year Month Symbol Adj Close
0 2019-01-03 2019 1 MSFT 24.42
2 2019-01-04 2019 1 MSFT 25.00
4 January 5, 2019 MSFT 25.25
6 January 6, 2019 MSFT 25.64
.. ... ... ... ... ...
491 2019-12-24 2019 12 MSFT 25.38
493 2019-12-26 2019 12 MSFT 25.20
495 2019-12-27 2019 12 MSFT 25.29
496 2019-12-28 2019 12 MSFT 24.91
[249 rows x 5 columns]
Grouping can be done on multiple columns by passing a list of
column names. The following command groups the data by the variables
Symbol, Year and Month:
In [42]:
mcg = [Link](['Symbol', 'Year', 'Month'])
print_groups(mcg)

Out[42]:
Date Year Month Symbol Adj Close
1 2019-01-03 2019 1 AAPL 55.41
3 2019-01-04 2019 1 AAPL 55.71
5 2019-01-05 2019 1 AAPL 56.33
7 2019-01-06 2019 1 AAPL 56.92
9 2019-01-09 2019 1 AAPL 56.83

Date Year Month Symbol Adjusted Close


41 2019-02-01 2019 2 AAPL 61.47
43 2019-02-02 2019 2 AAPL 61.33
45 2019-02-03 2019 2 AAPL 61.94
46 2019-02-06 2019 2 AAPL 62.52
48 2019-02-07 2019 2 AAPL 63.18
(’AAPL’, 2019, 3)
...
Since several columns were specified, the name of each group is now
a tuple with the value of Symbol, Year, and Month that represents the group.
The examples so far have used a DataFrame with no indexing.
specific. This type of data would be really very suitable for an index
hierarchical, which can be used directly to group the data based
two in the index label(s). To demonstrate this, the following command
create a new DataFrame with a MultiIndex that consists of the columns
Symbol, Original Year and Month.

Yessenia Portal Machuca 118 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

In [43]:
mi = s4g.set_index(['Symbol','Year','Month'])
my

Out[43]:

Symbol Year Month Date Adj Close


MSFT 2019 1 2019-01-03 24.42
AAPL 2019 1 2019-01-03 55.41
MSFT 2019 1 2019-01-04 25.00
AAPL 2019 1 2019-01-04 55.71
... ... ...
12 2019-12-27 70.02
MSFT December 2019 2019-12-27 25.29
12 2019-12-28 24.91
AAPL 2019 12 2019-12-28 69.28
[498 rows x 2 columns]

Now you can perform grouping using the levels of the hierarchical index.
quico. The following groups by index level 0.
In [44]:
mig_l1 = [Link](level=0)
print_groups(mig_l1)

Out[44]:
Symbol Year Month Date Adj Close
AAPL 2019 1 2019-01-03 55.41
1 2019-01-04 55.71
1 2019-01-05 56.33
1 2019-01-06 56.92
1 2019-01-09 56.83

Symbol Year Month Date Adj Close


MSFT 2019 1 2019-01-03 24.42
1 2019-01-04 25.00
1 2019-01-05 25.25
1 2019-01-06 25.64
1 2019-01-09 25.31

Yessenia Portal Machuca 119 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Grouping by multiple levels can be done by indicating multiple ni-


you want to groupby(). In addition, if the MultiIndex has specified names,
so those names can be used instead of the integers for the
levels. For example:
In [45]:
mig_l12 = [Link](level=['Symbol','Year','Month'])
print_groups(mig_l12)

Out[45]:
Symbol Year Month Date Adj Close
AAPL 2019 1 2019-01-03 55.41
1 2019-01-04 55.71
1 2019-01-05 56.33
1 2019-01-06 56.92
1 2019-01-09 56.83
...

Symbol Year Month Date Adj Close


MSFT 2019 12 2019-12-03 24.79
12 2019-12-04 24.74
12 2019-12-05 25.02
12 2019-12-06 25.07
12 2019-12-07 24.82

[Link]

Aggregation is done using the function .aggregate(), or in summary


.agg(), from the GroupBy object. For example:
In [46]:
mig_l12.agg([Link])

Out[46]:

Symbol Year Month Adj Close


AAPL 2019 1 57.75
2 67.05
3 77.82
4 81.66
... ...
MSFT September 2019 28.64
10 27.04
11 26.00
12 25.31
[24 rows x 1 columns]

Yessenia Portal Machuca 120 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

The result of the aggregation will have an index identical to that of the original data.
If you do not want this to happen, you can use the option as_index=False.
[Link]() to specify that the index structure is not duplicated.
In [47]:
[Link](['Symbol', 'Year', 'Month'],
as_index=False).agg([Link])[:5

Out[47]:

Symbol Year Month Adj Close


0 AAPL 2019 1 57.75
1 AAPL 2019 2 67.05
2 AAPL 2019 3 77.82
3 AAPL 2019 4 81.66
4 AAPL 2019 5 76.09

It is possible to apply multiple aggregation functions to each group in a single


code block of .agg() indicating a list. For example:
In [48]:
mig_l12.agg([[Link], [Link]])

Out[48]:
Symbol Year Month mean std
AAPL 2019 1 57.75 1.80
2 67.05 3.57
3 77.82 4.16
4 81.66 3.06
... ... ...
MSFT 2019 9 28.64 0.43
10 27.04 0.67
11 26.00 1.00
12 25.31 0.36
[24 rows x 2 columns]

Yessenia Portal Machuca 121 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

14. Matplotlib
14.1. Introduction
Matplotlib is a package for creating graphs and visualizing data. The architecture
matplotlib is structured in three layers, which are placed at three different levels.
Communication is unidirectional, meaning each layer can communicate with the layer
underlying.

Backend Layer: the layer that operates at the lowest level is the backend layer.
This layer contains the matplotlib APIs and a set of classes that play the role
of the implementation of graphic elements at a low level.
Artist Layer: in this layer are all the elements that make up a
graphic, such as the title, axis labels, markers, etc. Each element of a
The graphic corresponds to this artistic layer.

Scripting Layer (pyplot): for calculation purposes, and in particular for analysis
and data visualization, the interface layer called pyplot is the best. These
functions provide Python programmers with capabilities similar to those of
MATLAB.

Pylab and Pyplot.


Pylab is a module that is installed along with matplotlib, while pyplotes
An internal module of [Link] combines the functionality of pyplot with the
NumPy capabilities, therefore, does not need to import NumPy separately.
The pyplot package provides the classic Python interface, it has its own space
names and requires the import of NumPy separately.

Yessenia Portal Machuca 122 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

14.2. Pyplot
The pyplot module is a set of functions that allow you to use matplotlib.
very similar to MATLAB.
It will start with a simple graphic, importing the pyplot module, which in general
it is renamed comoplt. Therefore, you can simply pass the values you want
represent as a sequence of integers and these are associated with the sequence
natural values of the axis: 0,1,2,3.... See the following example:

In [1]: import [Link] as plt


In [2]: [Link]([1,2,3,4])
In [3]: [Link]()

Finally, the function show() is used to display a graphics window.


sitting inside it; this window is characterized by a toolbar,
at the top with a set of buttons, which are described below:

Icon Description

Restore the original list


Go to previous / next view
Full screen
Zoom rectangular
Subgraph configuration
Save Figure
Edit the axes

Yessenia Portal Machuca 123 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Generalmente un gráfico representa pares de valores(x,y), por lo que para definir


A graph correctly must define two matrices: the first that contains the values
in the x-axis the second that contains the values in the y-axis. In the generated graph, the
The x-axis will have values from 0 to (n-1) and the y-axis will have the values from the given list.
The properties of the graph are:

The size of the axes fits perfectly within the range of the input data.

The line connecting the points is drawn.

You can include a title, axis labels, legends, etc.

The objects that make up a graph have many attributes that characterize them. All
the attributes are default values, but they can be configured using
arguments, often referred to as kwargs. These keywords are defined as
arguments to functions. Example of a line graph.

[Link](*args, **kwargs)
In [4]: [Link]([1,2,4,2,1,0,1,2,1,4], linewidth=2.0)

14.3. Multiple figures


Matplotlib allows you to handle multiple figures simultaneously, and within a
same time span, each figure offers the possibility to see different graphs
defined as subgraphs. Therefore, when using pyplot, one must always keep in mind
the concept of the current figure and the current axes. The function subplot(), in addition to
divide the figure into different drawing areas, it is used to focus the commands on
a specific subplot.
The argument declared in the subplot() function sets the subdivision mode.
and determine what the current subgraph is. This subgraph will be the only area that will be visible.
affected by the commands. The argument of the function subplot() is composed of
three integers: the first number defines into how many parts the figure is divided
in vertical form, the second number defines how many parts it is divided into
horizontally, the third selects which is the current subgraph on which it
you can execute the commands.

Yessenia Portal Machuca 124 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Example of subgraphics.
In [5]: t = [Link](0,5,0.1)
y1 = [Link](2*[Link]*t)
y2 = [Link](2*[Link]*t)
In [6]: [Link](211)
[Link](t,y1,'b-.')
[Link](212)
[Link](t, y2, 'r--')
Out[6]: [<[Link].Line2D at 0xd47f518>]

The same can be done by dividing the figure into two horizontal subgraphs. The
The sentence and arguments are as follows:
In [7]: t = [Link](0., 1., 0.05)
y1 = [Link](2*[Link]*t)
y2 = [Link](2*[Link]*t)
In [8]: [Link](121)
[Link](t, y1, 'b-.')
[Link](122)
[Link](t,y2,'r--')
[<[Link].Line2D at 0xed0c208>]

Yessenia Portal Machuca 125 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

14.4. Elements of the graph


For a graph to be more informative, additional elements are required to
to enrich it, the most utilized are detailed below.

[Link]
To include a title in a graph, the title() function is used.

To add axis labels, it is possible by using two other functions.


specific: xlabel() and ylabel(). These functions take as an argument
a string, which will be the displayed text.

Example of a graph with a title and axis names.


In [9]: [Link]([0,5,0,20])
[Link]('My first plot')
[Link]('Counting')
[Link]('Square values')
[Link]([1,2,3,4],[1,4,9,16],'ro')
Out[9]: [<[Link].Line2D at 0x990f3c8>]

Yessenia Portal Machuca 126 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

It is also possible to modify the color of the axis labels, modify the title.
changing the font and increasing the size of the characters to emphasize the title
of the graphic, as shown below:

In [10]: [Link]([0,5,0,20])
[Link](’My first plot’,fontsize=20,fontname=’Times New Roman’)
[Link]('Counting', color='gray')
[Link]('Square values', color='gray')
[Link]([1,2,3,4],[1,4,9,16],'ro')
Out[10]: [<[Link].Line2D at 0x11f17470>]

In addition, matplotlib is not limited to this: pyplot allows you to add text to any
position within a graph. This feature is performed by the function called
text(). The syntax is as follows:

text(x, y, s, fontdict=None, **kwargs)


The first two arguments are the coordinates of the location where it is desired.
put the text, 'text string that will be added', and fontdict (optional) is the
source you want to use. Finally, you can add the keywords that add
the label to each point of the graph. Because the first two arguments of the
function text() are the coordinates of the graph, you have to use the coordinates of
the four points of the graph slightly displaced on the y-axis.

Yessenia Portal Machuca 127 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Example of a chart with labels.


In [11]: [Link]([0,5,0,20])
[Link](’My first plot’,fontsize=20,fontname=’Times New Roman’)
[Link]('Counting', color='gray')
[Link]('Square values', color='gray')
[Link](1,1.5,'First')
[Link](2, 4.5, 'Second')
[Link](3,9.5,'Third')
[Link](4,16.5,'Fourth')
[Link]([1, 2, 3, 4], [1, 4, 9, 16], 'ro')
[<[Link].Line2D at 0x10f76898>]

As can be seen in the previous figure, each point on the graph has a labeling.
quiet. In addition, it is possible to include expressions in LaTeX, therefore it allows inserting
mathematical expressions in the graph. To do this, a LaTeX expression can be added.
the text between two characters $. Generally, it is necessary to precede the string that contains
LaTeX expressions with unar, which indicates raw text, to avoid sequences of
unintended escapes. Therefore, as an example, the formula can be added
what describes the trend followed by the point of the graph in the previous example and to be
enclosed in a colored frame.
Example of a graphic with LaTeX text.
In [12]: [Link]([0,5,0,20])
[Link](’My first plot’,fontsize=20,fontname=’Times New Roman’)
[Link]('Counting', color='gray')
[Link]('Square values', color='gray')
[Link](1,1.5,'First')
[Link](2,4.5,'Second')
[Link](3,9.5,'Third')
[Link](4,16.5,'Fourth')
[Link](1.1,12,r'$y = x^2$',fontsize=20,bbox={'facecolor':'yellow',
’alpha’:0.2})
[Link]([1,2,3,4],[1,4,9,16],'ro')
Out[12]: [<[Link].Line2D at 0x13920860>]

Yessenia Portal Machuca 128 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

14.4.2. Grid
Another element that can be added to a graph is a grid. Often, its
addition is necessary to better understand the position that each point has in the
chart. Adding a grid can be done using the function grid() with the
argumentoTrue.
Example of a graph with a grid.
In [13]: [Link]([0,5,0,20])
[Link](’My first plot’,fontsize=20,fontname=’Times New Roman’)
[Link]('Counting', color='gray')
[Link]('Square values', color='gray')
[Link](1,1.5,'First')
[Link](2,4.5,'Second')
Third
[Link](4,16.5,'Fourth')
[Link](1.1,12,r'$y = x^2$',fontsize=20,
bbox={’facecolor’:’yellow’,’alpha’:0.2})
[Link](True)
[Link]([1,2,3,4],[1,4,9,16],'ro')
Out[13]: [<[Link].Line2D at 0x10f76898>]

Yessenia Portal Machuca 129 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

14.4.3. Legend
Another very important component that must be present in any graph is
the [Link] provides the function legend() to add a legend
the graphic and a string that indicates the words with which you want them to be displayed
series.
For example, the name "First series" is assigned to the graphed data.
In [14]: [Link]([0,5,0,20])
[Link](’My first plot’,fontsize=20,fontname=’Times New Roman’)
[Link]('Counting', color='gray')
[Link]('Square values', color='gray')
[Link](2, 4.5, 'Second')
[Link](3,9.5,'Third')
Fourth
$y =x^2$
’alpha’:0.2})
[Link](True)
[Link]([1,2,3,4],[1,4,9,16],’ro’)
[Link](['First series'])
Out[14]: <[Link] at 0x16377550>

As shown in the previous figure, the legend is included in the upper corner.
default to the right. If you want to change this behavior, you must add some
kwargs. The position occupied by the legend is set by assigning numbers from 0 to 10.
alquargde blockage. Each of these numbers characterizes one of the corners of
graphic. A value of 1 is the default value, that is, the upper right corner. A
the following is the localization table to configure the position of the legend.

Yessenia Portal Machuca 130 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Localization Code in text string


0 best
1 upper-right
2 upper-left
3 lower-right
4 lower-left
5 right
6 center-left
7 center-right
8 lower-center
9 upper-center
10 center

In the following example, several series are graphed, each characterized by the function
plot() and the order in which they are defined correspond to the order of the text labels.
defined as arguments in the legend() function.

In [15]: import [Link] as plt


[Link]([0, 5, 0, 20])
[Link]('My first plot', fontsize=20, fontname='Times New Roman')
[Link]('Counting', color='gray')
[Link](’Square values’,color=’gray’)
[Link](1,1.5,'First')
[Link](2,4.5,'Second')
[Link](3,9.5,'Third')
[Link](4,16.5,'Fourth')
[Link](1.1,12,'$y = x^2$',fontsize=20,
bbox={’facecolor’:’yellow’,’alpha’:0.2})
[Link](True)
[Link]([1,2,3,4],[1,4,9,16],'ro')
[Link]([1,2,3,4],[0.8,3.5,8,15],'g^')
[Link]([1,2,3,4],[0.5,2.5,4,12],'b*')
[Link](['First series', 'Second series', 'Third series'], loc=2)
Out[15]: <[Link] at 0x1828d7b8>

Yessenia Portal Machuca 131 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

14.5. Tipos de gráficos


The following describes and develops examples of different types of graphs that
they can be done with the Matplotlib package, starting with the most common ones,
such as line graphs, bar graphs, and pie charts, up to a discussion about
some that are more sophisticated and are commonly used.

14.5.1. Line graphs


Among all types of charts, the line chart is the simplest. A chart of
Lines are a sequence of data points connected by a line, each point of
data consists of a pair of values (x,y), which will be reported on the graph accordingly
on the value scale of the two axes (x and y).
As an example, a graph is created for the following mathematical function.
nérica:

y= sine(3∗ x)/x
Therefore, two numeric matrices are created.
Matrix that contains the dex values: to define a sequence of values
Clients will use the function [Link](), and given that the mathematical function is
sinusoidal, reference should be made to values that are multiples and submultiples of
pi ([Link]).

Matrix that contains the values of y: the values of y can be obtained by applying
the function [Link]() directly to these values.
Finally, the graph is created with the function plot().
In [16]: import [Link] as plt
import numpy as np
x = [Link](-2*[Link], 2*[Link], 0.01)
y = [Link](3*x)/x
[Link](x,y)
Out[16]: [<[Link].Line2D at 0x22404358>]

Yessenia Portal Machuca 132 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

As another example, the case of the mathematical function can be expanded to the following
equation:

y= sin(n∗ x)/x

Example of multiseries graph, varying the parameter n.


In [17]: import [Link] as plt
import numpy as np
x = [Link](-2*[Link], 2*[Link], 0.01)
y = [Link](3*x)/x
y2 = [Link](2*x)/x
y3 = [Link](3*x)/x
[Link](x,y)
[Link](x,y2)
[Link](x,y3)

In the following graph, it is seen that a different color is automatically assigned to


each data series. All the graphs are represented on the same scale; that is,
The data points of each series refer to the same x-axis and the same y-axis. This is
each call to the function plot() must take into account previous calls
to the same function, so the graph applies the changes while maintaining the memory of
the previous commands until the graph is not displayed.
Remember that to display the graph, you must use the show() function.

Yessenia Portal Machuca 133 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

14.5.2. Line graphs with pandas


Now it is detailed how to apply the matplotlib package to the data DataFrames of the
Pandas package. Visualizing data as a line graph is an operation.
very simple, you just need to provide the DataFrame data as an argument to
the plot() function to obtain a multiseries line graph.

Example of multiseries graph.


In [18]: import [Link] as plt
import numpy as np
import pandas as pd
data = {’series1’:[1,3,4,3,5],
’series2’:[2,4,5,2,4],
’series3’:[3,2,3,1,3]}
df = [Link](data)
x = [Link](5)
[Link]([0,5,0,7])
[Link](x,df)
[Link](data, loc=2)

Yessenia Portal Machuca 134 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

14.5.3. Histograms
A histogram consists of adjacent rectangles on the x-axis, divided into intervals
discrete called "bins", and with an area proportional to the frequency of occurrences
To represent a histogram, pyplot provides a special function called
hist(). This plotting function has a characteristic that other functions do not have. The
funcionhist(), besides drawing the histogram, returns a tuple of values that are
the results of the histogram calculation. The hist() function can perform the calculation
of the histogram, that is, it is sufficient to provide a series of sample values.
as an argument and the number of locations to be divided, and the function
will be responsible for dividing the sample range into many intervals, and then the calculations will be made
occurrences for each "bins".
Example: An array of 100 random values from 0 to 100 is generated using the function
aleatoriarandint(), and it is divided into 20 "bins". If the "bins" are not specified, the value
The default is 10.

In [19]: import [Link] as plt


import numpy as np
pop = [Link](0,100,100)
pop
Out[19]:
array([32, 14, 55, 33, 54, 85, 35, 50, 91, 54, 44, 74, 77, 6, 77, 74, 2,
54, 14, 30, 80, 70, 6, 37, 62, 68, 88, 4, 35, 97, 50, 85, 19, 90,
65, 86, 29, 99, 15, 48, 67, 96, 81, 34, 43, 41, 21, 79, 96, 56, 68,
49, 43, 93, 63, 26, 4, 21, 19, 64, 16, 47, 57, 5, 12, 28, 7, 75
6, 33, 92, 44, 23, 11, 61, 40, 5, 91, 34, 58, 48, 75, 10, 39, 77,
70, 84, 95, 46, 81, 27, 6, 83, 9, 79, 39, 90, 77, 94, 29])
In [20]: n, bins, patches = [Link](pop, bins=20)

Yessenia Portal Machuca 135 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

14.5.4. Gráficos de barras


Another very common type of chart is the bar chart. It is very similar to a histogram.
grammar, but in this case the example is used to reference numerical values instead
categories. Creating a bar chart is very simple with matplotlib, using the
functionbar().
Example of a bar graph.
In [21]: import [Link] as plt
index = [0,1,2,3,4]
values = [5,7,3,4,6]
[Link](index, values)
Output of 5 artists

In the previous graph, it can be seen that the indices are drawn on the x-axis.
dialog box at the beginning of each bar. In reality, because each bar corresponds
to a category, it would be better if the categories are specified through the label of
verification, defined by a list of text strings with the function xticks().
In [22]: import numpy as np
index = [Link](5)
values1 = [5,7,3,4,6]
[Link](index, values1)
[Link](index+0.4,['A','B','C','D','E'])

Yessenia Portal Machuca 136 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

There are many options to further refine the bar chart. Each one
These details are configured by adding a specific 'unkwarge' as an argument in the
function bar() .
For example, the standard deviation values of the bar can be added through
delyerr kwarg together with a list that contains the standard deviations. This kwarg
it is usually combined with another kwarg called error_kw, which in turn accepts other kwargs
specialized to represent error bars. Two very specific kwargs used
in this case soneColor, which specifies the color of the error bars, and capsize, which
define the width of the cross lines that mark the ends of the error bars.

Another kwarg you can use is alpha, which indicates the degree of transparency of the
color bar, alpha is a value that ranges from 0 to 1. When this value is 0, the object is
completely transparent to gradually become more significant with the increase
of the value, until reaching 1. As usual, it is recommended to use a legend,
so in this case the legend() argument should be used to identify the series that
it is being represented.
Example of a bar graph with error bars.
In [23]: import numpy as np
index = [Link](5)
values1 = [5,7,3,4,6]
std1 = [0.8,1,0.4,0.9,1.3]
A Bar Chart
[Link](index, values1, yerr=std1, error_kw={'ecolor': '0.1',
’capsize’:6},alpha=0.7,label=’First’)
[Link](index+0.4,[ 'A', 'B', 'C', 'D', 'E' ])
[Link](loc=2)

Yessenia Portal Machuca 137 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

14.5.5. Horizontal bar charts


There are also horizontal bar graphs. This mode is simple
mentioned by a special function called barh(). The valid arguments and kwargs
for the function bar() they remain the same for this function. The only change that
It should be noted that the roles of the axes are reversed. Now, the categories
They are represented on the y-axis, and the numerical values are shown on the x-axis.

Example of a horizontal bar chart.


In [24]: import [Link] as plt
import numpy as np
index = [Link](5)
values1 = [5,7,3,4,6]
std1 = [0.8,1,0.4,0.9,1.3]
A Horizontal Bar Chart
[Link](index, values1, xerr=std1, error_kw={'ecolor':'0.1',
{"capsize":6,"alpha":0.7,"label":"First"}
[Link](index+0.4,['A','B','C','D','E'])
[Link](loc=5)

Like line graphs, bar graphs are also generally used to


simultaneously display larger series of values. But in this case it is necessary
make some clarifications about how to structure a multiseries bar chart. In
In this case, there are several bars that must share the same category. An approach
used to overcome this problem is to divide the space occupied by an index (by
convenience its width is 1) in as many parts as the bars that share that index
and that we want to show. Additionally, it is advisable to add space, which will help to separate.
a category with respect to the following.

Yessenia Portal Machuca 138 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Example of vertical multi-series bar chart.


In [25]: import [Link] as plt
import numpy as np
index = [Link](5)
values1 = [5,7,3,4,6]
values2 = [6,6,4,5,7]
values3 = [5,6,5,4,6]
bw = 0.3
[Link]([0,5,0,8])
[Link]('A Multiseries Bar Chart', fontsize=20)
[Link](index, values1, bw, color='b')
[Link](index+bw, values2, bw, color='g')
[Link](index + 2 * bw, values3, bw, color='r')
[Link](index + 1.5 * bw, ['A', 'B', 'C', 'D', 'E'])

Regarding the horizontal multi-series bar chart, the code is very similar, only
the function bar() must be replaced by the corresponding function barh() and do not forget
replace the xticks() function with the yticks() function. It is necessary to reverse the range
of values that cover the axes in the function axis().
Example of a horizontal multiseries bar chart.
In [26]: import [Link] as plt
import numpy as np
index = [Link](5)
values1 = [5,7,3,4,6]
values2 = [6,6,4,5,7]
values3 = [5,6,5,4,6]
bw = 0.3
[Link]([0,8,0,5])
[Link](’A Multiseries Horizontal Bar Chart’,fontsize=20)
[Link](index, values1, bw, color='b')
[Link](index+bw, values2, bw, color='g')
[Link](index+2*bw,values3,bw,color='r')
[Link](index + 0.4, ['A', 'B', 'C', 'D', 'E'])

Yessenia Portal Machuca 139 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

14.5.6. Multi-series bar charts with pandas DataFrame


To directly plot the data from a DataFrame, you can use the function
plot() applied to the DataFrame object and specify within a kwarg called kind,
the type of graph that needs to be represented.
Example of a multiseries bar chart.
In [27]: import [Link] as plt
import numpy as np
import pandas as pd
data = {’series1’:[1,3,4,3,5],
’series2’:[2,4,5,2,4],
’series3’:[3,2,3,1,3]}
df = [Link](data)
[Link](kind='bar')

Regarding the horizontal bar chart, the same rules can be applied,
just remember to set establishbarh() as the value of the kwarg type.

Yessenia Portal Machuca 140 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

14.5.7. Stacked bar charts of multiple series


Another way to represent a multi-series bar graph is in a stacked form,
in which the bars are stacked one on top of the other. This is especially useful when
wants to show the total value obtained by the sum of all the bars. To transform
a simple multi-series bar chart into a stacked one, add the kwarg bottom to each
functionbar(). Each series must be assigned to the corresponding kwarg bottom. In the end
you will obtain the stacked bar chart. For example:

In [28]: import [Link] as plt


import numpy as np
series1 = [Link]([3,4,5,3])
series2 = [Link]([1,2,2,5])
series3 = [Link]([2,3,3,4])
index = [Link](4)
[Link]([-0.5,3.5,0,15])
A Multiseries Stacked Bar Chart
[Link](index, series1, color='r')
[Link](index, series2, color='b', bottom=series1)
[Link](index, series3, color='g', bottom=(series2 + series1))
[Link](index+0.4,['Jan18','Feb18','Mar18','Apr18'])

Yessenia Portal Machuca 141 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

To create the equivalent horizontal stacked bar chart, the must be replaced
function bar() for the function barh(), taking into account to also change the others.
parameters. In fact, the function xticks() should be replaced by the function
yticks(), since the category labels must now be reported on the y-axis.

After making all these changes, you will get the horizontal bar chart api-
side as shown below, as an example:
In [29]: import [Link] as plt
import numpy as np
index = [Link](4)
series1 = [Link]([3,4,5,3])
series2 = [Link]([1,2,2,5])
series3 = [Link]([2,3,3,4])
[Link]([0,15,-0.5,3.5])
A Multiseries Horizontal Stacked Bar Chart
[Link](index, series1, color='r')
[Link](index, series2, color='g', left=series1)
[Link](index, series3, color='b', left=(series1 + series2))
[Link](index+0.4,[‘Jan18’,‘Feb18’,‘Mar18’,‘Apr18’])

14.5.8. Stacked bar charts with a pandas DataFrame


Regarding stacked bar charts, it is very simple to represent directly
specifically the values contained in a DataFrame object using the plot() function.
You just need to add as an argument the stacked elkwarg configured with the argument
True.

Yessenia Portal Machuca 142 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

For example:
In [31]: import [Link] as plt
import pandas as pd
data = {’series1’:[1,3,4,3,5],
’series2’:[2,4,5,2,4],
’series3’:[3,2,3,1,3]}
df = [Link](data)
[Link](kind='bar', stacked=True)
Out[31]: <[Link]._subplots.AxesSubplot at 0xcda8f98>

14.5.9. Other Representations of Bar Graphs


Another very useful type of representation is the bar graph for comparison, in
for which two series of values that share the same categories are compared by placing
the bars in opposite directions along the y-axis. For this, the values must be obtained.
give one of the two series in a negative form.
To color the interior of the bars differently, it can be done.
setting the two different colors in the kwarg:facecolor. Also, that can
add the value and with a label in the extreme dialog window of each bar,
using a for loop where the function text().
Finally, the position of the label can be adjusted with the kwargs called
hayva, which control the horizontal and vertical alignment, respectively.

Yessenia Portal Machuca 143 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Below is an example.
In [32]: import [Link] as plt
x0 = [Link](8)
y1 = [Link]([1,3,4,6,4,3,2,1])
y2 = [Link]([1,2,5,4,3,3,2,1])
[Link](-7,7)
[Link](x0, y1, 0.9, facecolor='r')
[Link](x0, -y2, 0.9, facecolor='b')
[Link](())
[Link](True)
for x, y in zip(x0, y1):
[Link](x + 0.4, y + 0.05, '%d' % y, ha='center', va='bottom')

forx, yin zip(x0, y2):


[Link](x + 0.4, -y - 0.05, '%d' % y, ha='center', va='top')

14.5.10. Gráficos de Pie


An alternative way to display data is the pie chart, which can be obtained
easily using the pie() function. Even for this type of function, it is passed as
main argument a list that contains the values that should be displayed. The function
pie() will inherently calculate the percentage that each value occupies.
Also with this type of representation, it is necessary to define some characteristics.
key using kwargs. For example, if you want to define the sequence of the
colors, which will be assigned to the sequence of input values correspondingly,
you must use kwarg:colors. Therefore, you must assign a list of strings, each one
of which contains the name of the desired color.
Another important feature is to add labels to each part of the foot, for which
you should use the kwarg tags to which you will assign a list of strings containing
the labels that will be displayed in sequence. In addition, to draw the pie chart of
perfectly spherical shape, you need to add the function axis() at the end of the statement,
specifying the string as an argument.

Yessenia Portal Machuca 144 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

The following example is given.


In [33]: import [Link] as plt
labels = [’Nokia’,’Samsung’,’Apple’,’Lumia’]
values = [10,30,45,15]
colors = [’yellow’,’green’,’red’,’blue’]
[Link](values, labels=labels, colors=colors)
[Link]('equal')

To add complexity to the pie chart, you can draw it with a part extracted from
pie. For this, there is a special kwarg called explode. It is nothing more than a sequence
of values 0 or 1, where 1 corresponds to the fully extended portion and 0
corresponds to the complete parts in the foot. The angle can also be adjusted.
rotation of the figure adding the kwarg:startangle, which takes an integer value between
0 and 360, which are the degrees of rotation with precision, where 0 is the default value.
Example of a pie chart with a part extracted.
In [34]: import [Link] as plt
labels = [’Nokia’,’Samsung’,’Apple’,’Lumia’]
values = [10,30,45,15]
colors = [’yellow’,’green’,’red’,’blue’]
explode = [0.3,0,0,0]
A Pie Chart
[Link](values, labels=labels, colors=colors, explode=explode,
startangle=180)
[Link]('equal')

Yessenia Portal Machuca 145 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Moreover, the kwarg:autopct can be used, which adds to the center of each part of the
draw a text label that shows the corresponding value. Finally, one can
add a shadow the Kwarg: shadow configuring it to True. For example:
In [35]: import [Link] as plt
labels = [’Nokia’,’Samsung’,’Apple’,’Lumia’]
values = [10,30,45,15]
colors = [’yellow’,’green’,’red’,’blue’]
explode = [0.3,0,0,0]
A Pie Chart
[Link](values, labels=labels, colors=colors, explode=explode,
shadow=True, autopct='%1.1f%%', startangle=180)
[Link]('equal')

Yessenia Portal Machuca 146 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

14.5.11. Pie charts with a pandas DataFrame


To graph data from an ObjectDataFrame, in this case, it can only be represented
one series at a time. You must specify the type of graph you want to represent through the
kwarg:kind, in the plot() function, which in this case is spy.
For example:
In [36]: import [Link] as plt
import pandas as pd
data = {’series1’:[1,3,4,3,5],’series2’:[2,4,5,2,4],
’series3’:[3,2,3,1,3]}
df = [Link](data)
df['series1'].plot(kind='pie', figsize=(6,6))
Out[36]: <[Link]._subplots.AxesSubplot at 0xe1ba710>

14.5.12. Advanced graphs: Polar


There is a wide variety of advanced alternative graphics that can be used.
grammar using Matplotlib6 however, below is only one example of
Polar graphics. This type of graphic is characterized by a series of sectors that are...
they extend radially; each of these areas occupies a certain angle; in this way, they
two different values can be visualized by assigning them to the magnitudes that characterize
to this graph: the extension of the radius and the angle θ occupied by the sector. These are the
coordinates(r,θ), an alternative way of representing functions on the axes of
coordinates.

This is a chart that has characteristics of both the pie chart and the chart.
of bars. In fact, like the pie chart, the angle of each sector provides information.
percentage represented by that category with respect to the total. Regarding the graph of
bars, the radial graph is the numerical value of that category.
6 For more details, please check:
[Link]
[Link]

Yessenia Portal Machuca 147 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Para obtener un gráfico polar se debe usar la funciónbar()e indicar la lista que
contains the angles θ and a list of the radial extent of each sector.

It is important to remember that the color of the graph can be defined with a list of
string values containing RGB codes in the format #rrggbb
to the colors that are desired.

Below is an example of a polar graph.


In [37]: import [Link] as plt
import numpy as np
N = 8
theta = [Link](0., 2 * [Link], 2 * [Link] / N)
radii = [Link]([4,7,5,3,1,5,6,7])
[Link]([0.025, 0.025, 0.95, 0.95], polar=True)
colors = [Link]([’#4bb2c5’,’#c5b47f’,’#EAA228’,’#579575’,
’#839557’,’#958c12’,’#953579’,’#4b5de4’])
bars = [Link](theta, radii, width=(2*[Link]/N), bottom=0.0,
color=colors)

Yessenia Portal Machuca 148 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

14.6. 3D Graphics
The mplot3d module also uses the Figure object, only that instead of axes it will define
a new type of object, called Axes3D. Therefore, it is necessary to import this module
to use the Axes3D object.
from mpl_toolkits.mplot3d import Axes3D

14.6.1. 3D Surface
With the paquetemplot3D, surfaces can be drawn directly in 3D.
For example, the function z = f(x, y) is graphed, and the surface can be seen with the function.
plot_surface().
In [39]: from mpl_toolkits.mplot3d import Axes3D
import [Link] as plt
fig = [Link]()
ax = Axes3D(fig)
X = [Link](-2, 2, 0.1)
Y = [Link](-2, 2, 0.1)
X,Y = [Link](X,Y)
deff(x,y):
return(1 - y**5 + x**5)*[Link](-x**2-y**2)
ax.plot_surface(X,Y,f(X,Y), rstride=1, cstride=1)

A 3D surface stands out more by changing the color map, for example, it can be
set the kwarg cmap option. You can also rotate the surface using the function
view_init(). In fact, this adjusts the viewpoint from which the surface is seen,
changing the kwargs: elevyazim. Through their combination one can obtain the
surface shown from any angle. The first kwarg adjusts the height at which it
it sees the surface, while the second adjusts the rotation angle of the surface.

Yessenia Portal Machuca 149 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Below is an example.
In [40]: from mpl_toolkits.mplot3d import Axes3D
import [Link] as plt
fig = [Link]()
ax = Axes3D(fig)
X = [Link](-2,2,0.1)
Y = [Link](-2, 2, 0.1)
X,Y = [Link](X,Y)
def(x,y): return(1 - y**5 + x**5)*[Link](-x**2-y**2)
ax.plot_surface(X,Y,f(X,Y), rstride=1, cstride=1, cmap=[Link])
ax.view_init(elev=30, azim=125)

14.6.2. 3D Bar Charts


Another type of 3D graphic widely used in data analysis is the graph of
3D bars. Also in this case, the function bar() is used applied to the Axes3D object.
If several series are defined, multiple calls to the function bar() can accumulate in the
same 3D visualization. For example:
In [41]: import [Link] as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
x = [Link](8)
y = [Link](0,10,8)
y2 = y + [Link](0,3,8)
y3 = y2 + [Link](0,3,8)
y4 = y3 + [Link](0,3,8)
y5 = y4 + [Link](0,3,8)
clr = [’#4bb2c5’,’#c5b47f’,’#EAA228’,’#579575’,’#839557’,
’#958c12’,’#953579’,’#4b5de4’]
fig = [Link]()
ax = Axes3D(fig)

Yessenia Portal Machuca 150 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

[Link](x,y,0,zdir='y',color=clr)
[Link](x, y2, 10, zdir='y', color=clr)
[Link](x, y3, 20, zdir='y', color=clr)
[Link](x,y4,30,zdir='y',color=clr)
[Link](x,y5,40,zdir='y',color=clr)
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Z Axis')
ax.view_init(elev=40)

14.7. Gráficos Multi-Panel


14.7.1. Visualize subplots within other subplots
The ability to see graphs within others, enclosed within frames, is ne-
it is necessary to separate the main axes (that is, the general graph) from the framework that one wants
add, that it will be another instance of axes. For this, the figures() function is used to
obtain the object on which two objects with different axes will be defined using the
function add_axes(). For example:
In [43]: import [Link] as plt
import numpy as np
fig = [Link]()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
inner_ax = fig.add_axes([0.6,0.6,0.25,0.25])
x1 = [Link](10)
y1 = [Link]([1,2,7,1,5,2,4,2,3,1])
x2 = [Link](10)
y2 = [Link]([1,3,4,5,4,5,2,6,4,3])
[Link](x1,y1)
inner_ax.plot(x2, y2)
Out[43]: [<[Link].Line2D at 0x14acf6d8>]

Yessenia Portal Machuca 151 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

14.7.2. Subplot Grids


The GridSpec() function allows dividing the drawing area into a grid of subplots.
nas, to which one or more can be assigned to each subplot, so that in the end
Subplots of different sizes and orientations can be obtained. You can use the
Axes object for each function add_subplot() to call the plot() function and draw
the corresponding graphic. For example:
In [45]: import [Link] as plt
import numpy as np
gs = [Link](3,3)
fig = [Link](figsize=(6,6))
x1 = [Link]([1,3,2,5])
y1 = [Link]([4,3,7,2])
x2 = [Link](5)
y2 = [Link]([3,2,4,6,4])
s1 = fig.add_subplot(gs[1,:2])
[Link](x,y,'r')
s2 = fig.add_subplot(gs[0,:2])
[Link](x2,y2)
s3 = fig.add_subplot(gs[2,0])
[Link](x2, y2, color='g')
s4 = fig.add_subplot(gs[:2,2])
[Link](x2, y2, 'k')
s5 = fig.add_subplot(gs[2,1:])
[Link](x1, y1, 'b^', x2, y2, 'yo')

Yessenia Portal Machuca 152 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

15. Packages for financial applications


15.1. Statsmodels
It is a package that provides widely used statistical models, which focuses
more in the statistics and underlying diagnostics than in the models
more advanced or predictive. This package has dependencies on the NumPy packages,
pandas, scipy, Cython must be installed. To install this package
you must run the following command in the Anaconda Prompt console.
pip install statsmodels

The statsmodels package contains the following modulesthe7 .

Linear Regression Methods for Survival and Duration


Analysis
Generalized Linear Models Statistics stats

Generalized Estimating Equations Nonparametric Methods nonparame-


tric

Generalized Additive Models (GAM) Generalized Method of Moments


gmm
Robust Linear Models Contingency tables

Multiple Imputation with Chained


Linear Mixed Effects Models
Equations

Regression with Discrete Dependent Multivariate Statistics multivariate


Variable
Empirical Likelihood emplike

Generalized Linear Mixed Effects Model Other Models miscmodels


of them
Distributions

ANOVA Graphics Input-Output iolib

Tools
Time Series analysis tsa
The Datasets Package

Time Series Analysis by State Space Sandbox


Methods statespace
Working with Large Data Sets

Vector Autoregressions tsa.vector_ar Optimization

Some of the modules of this package will be reviewed as examples.

7 For more details see[Link]

Yessenia Portal Machuca 153 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

[Link] statistics
This package has a set of functions for descriptive statistics, co-
my part of the data exploration. Below is a list of the
main functions:

Functions Description
[Link](x[, unbiased, demean, fft, ...]) Autocovariance for 1D
[Link](x[, unbiased, nlags, qstat, . . . ]) Autocorrelation function for 1d arrays.
[Link](x[, nlags, method, alpha]) Estimated partial autocorrelation
stattools.pacf_ols(x[, nlags, efficient, . . . ]) Calculate partial autocorrelations using
OLS
[Link](x, y[, unbiased]) cross-correlation function for 1d
[Link](X) Return the periodogram for the frequency
natural of X
[Link](x[, maxlag, regression, . . . ]) Unit root test Dickey-Fuller
augmented
[Link](x[, regression, lags, store]) Stationarity test of
Kwiatkowski-Phillips-Schmidt-Shin
[Link](y0, y1[, trend, method, . . . ]) Test of no cointegration of an equation
univariate
stattools.q_stat(x, nobs[, type]) Statistics of Return’s Ljung-Box Q
stattools.levinson_durbin(s[, nlags, isacov]) Levinson-Durbin recursion for
autoregressive processes
stattools.innovations_algo(acov[, nobs, rtol]) Innovation algorithm for conversion
autocovariances to MA parameters
stattools.levinson_durbin_pacf(pacf[, nlags]) Levinson-Durbin algorithm that returns the
ACF and AR coefficients
stattools.arma_order_select_ic(y[, max_ar, ...]) Returns the information criteria for
many ARMA models

Interpolation
[Link] is a method used for
convert low frequency data to high frequency. The Denton method minimizes
the distance given by the penalty function, with least squares, between
the unknown reference series and the series of indicators subject to the condition
that the sum of the reference series is equal to the reference. If not available
from no reference point for the latest observations of the indicators,
the extrapolation is carried out using the latest reference indicator ratio of the
previous period.
Mathematically it is given:

X[t]I[t] − X[t − 1]I[t− 1])∗ ∗2

Minimize the sum

sum(X) = A

Yessenia Portal Machuca 154 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

For each period, whereXit is the reference series,Iit is the indicator andAis the
reference point.

This method has the following parameters.

Indicator: A series of low-frequency indicators. That is, the first


indicators align with the first benchmark.
Reference point: The most frequently occurring reference point.
Freq:str {"aq", "qm", "other"} la frecuencia de conversión
∗ Comparison of an annual series to a quarterly one.
∗ "mq": Benchmarking de una serie trimestral a mensual.
Kwargs: the number of high-frequency observations that are added to
make a low-frequency aggregated observation. k is used with freq ==
other

Example:
indicator = [50,100,150,100] * 5
benchmark = [500,400,300,400,500]
benchmarked = dentonm(indicator, benchmark, freq="aq")

3. Time Series Analysis


The module [Link] functions that are useful for analysis.
of time series. Basic models include univariate autoregressive models.
riados (AR), vector autoregressive models (VAR), and univariate models of
autoregressive moving average (ARMA). Non-linear models include regression
Markov switching dynamics and autoregression. It also includes methods-
two for working with moving average and autoregressive polynomials. In addition, they are
available statistical tests related. The estimation is made by probability-
maximum exact dad or conditional or by conditional least squares, whether
using the Kalman Filter or direct filters.

The structure of the module is:

stattools: properties and empirical tests, acf, pacf, granger-causality, adf


unit root test, kpss test, bds test, ljung-box test and others.
ar_model: univariate autoregressive process, estimation with probability
maximum conditional and exact, and conditional least squares.
arima_model: univariate ARMA process, estimation with maximum likelihood
conditional and exact maximum and conditional least squares.
vector_ar, var: vector autoregressive processes (VAR) and models of
vector error correction, estimation, impulse-response analysis
variance decomposition and data visualization tools.
kalmanf: estimation classes for ARMA and other models with exact MLE
using Kalman filter.

Yessenia Portal Machuca 155 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

arma_process:properties of ARMA processes with given parameters,


this includes tools to convert between ARMA representation, MA, and
AR as well as acf, pacf, spectral density and impulse response function.
tsatools: additional helper functions for creating variable matrices
lagging, build regressors for trends and similar.
regime_switching: Markov changes dynamic regression models and
autoregression.

[Link]
This principal component analysis module has the following parameters
tros:

data(array-like): Variables in columns, observations in rows


ncomp(int, optional): Number of components to return.
standardize(bool, optional): Indicador que indica que se deben utilizar da-
standardized scores with a mean of 0 and unit variance. The use of data
standardized is equivalent to calculating the principal components of the
correlation matrix of data.
demean(bool, optional): Indicator that indicates whether the data should be demeaned.
before calculating the principal components. degrading is ignored if the
standardization is True.
normalize(bool, optional): Indicates whether the factors are normalized to have
internal unit of product.
weights(array, optional): Weights in series to use after transforming
the data according to standardization or degradation when computing the
main components.
gls(bool, optional): Indicator that indicates the implementation of an estimator
Two-step GLS where in the first step the principal components are used.
to estimate the residuals, and then the inverse residual variance is used as a
set of weights to estimate the final principal components.
method(str, optional): Sets the linear algebra routine used to
Calculate the eigenvectors SVD uses a singular value decomposition.
gular (by default), 'eig' uses an eigenvalue decomposition of
a quadratic form, 'nipals' uses the NIPALS algorithm.
missing(string): Method for missing data.

The default options perform principal component analysis on


the degraded data version and unit variance. Once transformed the
data, the following relationships are maintained when the number of components
(ncomp) is the same as the minimum number of the number of observations or the number
of variables.

Yessenia Portal Machuca 156 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Example

a) Basic PCA using the data correlation matrix.


import numpy as np
from [Link] import PCA
x = [Link](100)[:, None]
x = x + [Link](100, 100)
pc = PCA(x)

Note that the main components are calculated using SVD and therefore
the correlation matrix is never built unless the
method'eig'.

b) PCA using the covariance matrix of the data


pc = PCA(x, standardize=False)

Limit the number of factors returned to 1, calculation using NIPALS.


pc = PCA(x, ncomp=1, method='nipals')
[Link] (100, 1)

Methods Description
plot_rsquare([ncomp, ax]) Boxplots of the individual series
R-squared against the number of PCs
Eigenvalue plot
ordered
project([ncomp, transform, unweight]) Series of projects in a number
specific factors

[Link]
Below is a summary of the main functions of the stat package.
models, to create different types of graphs.

a) Goodness of fit

Methods Description
[Link](data[, dist, distargs, a, . . . ]) Q-Q plot of the quantiles of x
in front of the quantiles/ppf of a
distribution
[Link](ax, line[, x, y, dist, fmt]) Draw a reference line for a
qqplot.
Q-Q Plot of the quantiles of two samples
samples.
[Link](data[, dist, fit, ...]) Class for construction
convenient Q-Q, P-P plots and
of probability.

b) Boxplots

Yessenia Portal Machuca 157 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

Methods Description
violin plot for each data set in
the data sequence.
[Link](data[, ax, labels, . . . ])Graph bean of each dataset in the
data sequence.

c) Correlation graphics

Methods Description
correlation.plot_corr(dcorr[, xnames, . . . ]) Trace the correlation of many variables in
a fitted color grid.
Create a correlation plot grid.
plot_grids.scatter_ellipse(data[, level, . . . ]) Create a grid of graphs
dispersion with confidence ellipses.

d) Functional graphics

Methods Description
[Link](data[, ncomp, alpha, . . . ])Boxplot of the high density region
[Link](data[, xdata, labels, ...]) Functional graph.
[Link](data[, xdata, depth, . . . ]) Creates a rainbow plot for a
set of curves.
[Link](data[, method]) Calculate the band depth for
a set of functional curves.

e) Regression graphics

Methods Description
regressionplots.plot_fit(results, exog_idx) Regression fit graph
regressionplots.plot_regress_exog(results, . . . )Graph the regression results against a
regressor.
regressionplots.plot_partregress(endog, . . . ) Partial regression plot for a single
regressor
regressionplots.plot_partregress_grid(results) Partial regression plot for a
set of regressors.
regressionplots.plot_ccpr(results, exog_idx) CCPR against a regressor.
regressionplots.plot_ccpr_grid(results[, . . . ]) Generate graphs of the CCPR against a
set of regressors, graphs in
grid.
regressionplots.plot_ceres_residuals(. . . [, . . . ]) Produce a CERES (Conditional
Expectation Partial Residuals) for a
fitted regression model.
regressionplots.abline_plot([intercept, ... ]) Draw a line given an intercept and a
pending.
regressionplots.influence_plot(results[, . . . ]) Influence plot in regression.
regressionplots.plot_leverage_resid2(results) Leverage statistics of graphs.

Yessenia Portal Machuca 158 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

f) Time series graphs

Methods Description
tsaplots.plot_acf(x[, ax, lags, alpha, . . . ]) Draw the autocorrelation function
tsaplots.plot_pacf(x[, ax, lags, alpha, . . . ])Plot the partial autocorrelation function
tsaplots.month_plot(x[, dates, ylabel, ax]) Seasonal graph of monthly data
Quarterly seasonal plot of the data

g) Other graphics

Methods Description
factorplots.interaction_plot(x, trace, response) Interaction graph for
factor level statistics.
[Link](data[, index, ax, . . . ]) Create a mosaic chart from
from a contingency table.
mean_diff_plot(m1, m2[, sd_limit, ...]) Mean difference plot.

15.2. Visualize Wealth


This is a package for building, backtesting, analyzing, and evaluating portfolios,
and its benchmarks. This package has the following dependencies: NumPy & scipy,
pandas, tables, urllib2. To install this package follow the instructions below:

1. Clone the repository (folder where the package has been saved).
$ cd ~/Downloads
$ git clone [Link]

2. Change the directory


$ cd wealth-viz

3. Install the package


$ python [Link] install

4. Check the installation by importing the package


import visualize wealth

This package includes the construction of portfolios using three methods:

The blotter method.

2. Weight assignment method.

3. Initial assignment and rebalancing method.

For more details of the package see[Link]

Yessenia Portal Machuca 159 yportal@[Link]


PROGRAMMING IN PYTHON
Basic Level

References
[1] H. [Link] Basics A Self-Teaching Introduction. Mercury, 2019.
David Jamieson Bolder. Credit-Risk Modelling: Theoretical Foundations, Diagnostic
Tools, Practical Examples, and Numerical Recipes in Python. Springer International
Publishing, 1st ed. edition, 2018.
Claus Fuher. Computing With Python: An Introduction to Python for Science &
Engineering. Pearson Education Limited, 2013.
Alex Galea. Applied Data Science with Python and Jupyter. Packt Publishing,
2018.
[5] Veena A. Gowrishankar [Link] to Python Programming. CRC, 2019.
[6] Magnus Lie [Link] Python: From Novice to Professional. Apress, 3rd
ed. edition, 2017.
Michael Heydt. Mastering pandas for Finance: Master pandas, an open source
Python Data Analysis Library, for financial data analysis. Packt Publishing, 2015.
Yves Hilpisch. Derivatives Analytics with Python: Data Analysis, Models, Simulation
tion, Calibration and Hedging. Wiley, 2015.
[9] Yves [Link] for Finance: Mastering Data-Driven Finance. O’Reilly Media,
2nd edition, 2019.
[10] Yves J [Link] for Finance: Analyze Big Financial Data. O’Reilly Media,
first edition edition, 2015.
[11] Pawel [Link] for Quants, volume 1. QuantAtRisk, 2015.
Eric Matthes. Python Crash Course A Hands-On, Project-Based Introduction to
Programming. No Starch Press, 2016.
[13] Bhaskar N. Das [Link] Python in 7 days : get up-and-running with Python.
Packt Publishing - ebooks Account, 2017.
[14] Fabio [Link] Data Analytics with Pandas, NumPy and Matplotlib [2nd ed.].
Apress, 2018.
[15] Ajay [Link] for R users : a data science approach. Wiley, 2018.
David J. Pine. Introduction to Python for Science and Engineering. Series in
Computational Physics. CRC Press, 2019.
Christopher Gardner Shayne Fletcher. Financial Modelling in Python (The Wiley
Finance Series). Wiley, 2009.
Ben Stephenson. The Python Workbook: A Brief Introduction with Exercises
Solutions. Texts in Computer Science. Springer, 2nd edition, August 2019.
[19] James Ma [Link] Python for Finance. Packt Publishing, 2015.
[20] Yuxing [Link] for Finance. Packt Publishing, 2nd edition, 2017.

Yessenia Portal Machuca 160 yportal@[Link]

You might also like