Introduction to Python for Econometrics, Statistics and Data Analysis. 5th Edition Kevin Sheppard. instant download
Introduction to Python for Econometrics, Statistics and Data Analysis. 5th Edition Kevin Sheppard. instant download
https://ebookmeta.com/product/introduction-to-python-for-
econometrics-statistics-and-data-analysis-5th-edition-kevin-
sheppard/
https://ebookmeta.com/product/statistics-for-data-scientists-an-
introduction-to-probability-statistics-and-data-analysis-maurits-
kaptein/
https://ebookmeta.com/product/introduction-to-statistics-and-
data-analysis-6th-edition-peck/
https://ebookmeta.com/product/introduction-to-python-in-earth-
science-data-analysis-1st-edition-maurizio-petrelli/
https://ebookmeta.com/product/social-media-marketing-a-strategic-
approach-2nd-edition-melissa-barker/
Essentials of Economics, 10e 10th Edition N. Gregory
Mankiw
https://ebookmeta.com/product/essentials-of-economics-10e-10th-
edition-n-gregory-mankiw/
https://ebookmeta.com/product/beginning-windows-mixed-reality-
programming-for-hololens-and-mixed-reality-headsets-2nd-edition-
sean-ong/
https://ebookmeta.com/product/an-introduction-to-economic-
dynamics-modelling-analysis-and-simulation-1st-edition-srinivas-
raghavendra/
https://ebookmeta.com/product/pokemon-heartgold-soulsilver-the-
official-pokemon-kanto-guide-national-pokedex-official-strategy-
guide-prima-official-game-guide-the-pokemon-company/
https://ebookmeta.com/product/become-a-competent-music-producer-
in-365-days-1st-edition-sam-george/
The Legal Effects of Recognition in International Law:
As Interpreted by the Courts of the United States John
G. Hervey
https://ebookmeta.com/product/the-legal-effects-of-recognition-
in-international-law-as-interpreted-by-the-courts-of-the-united-
states-john-g-hervey/
Introduction to Python for
Econometrics, Statistics and Data Analysis
5th Edition
Kevin Sheppard
University of Oxford
• Expanded coverage of random number generation and added coverage of the preferred method to gener-
ate random variates, numpy.random.Generator in chapter Simulating Random Variables.
• Verified that all code and examples work correctly against 2020 versions of modules. The notable pack-
ages and their versions are:
• Python 3.8 is the recommended version. The notes require Python 3.6 or later, and all references to
Python 2.7 have been removed.
• Removed references to NumPy’s matrix class and clarified that it should not be used.
• Verified that all code and examples work correctly against 2020 versions of modules. The notable pack-
ages and their versions are:
– Python 3.8 (Preferred version), 3.6 (Minimum version)
– NumPy: 1.19.1
– SciPy: 1.5.2
– pandas: 1.1.1
– matplotlib: 3.3.1
• Introduced f-Strings in Section 23.3.3 as the preferred way to format strings using modern Python. The
notes use f-String where possible instead of format.
• Added coverage of Windowing function – rolling, expanding and ewm – to the pandas chapter.
• Expanded the list of packages of interest to researchers working in statistics, econometrics and machine
learning.
• Expanded description of model classes and statistical tests in statsmodels that are most relevant for econo-
metrics. Added section detailing formula support. This list represents on a small function of the statsmod-
els API.
• Added minimize as the preferred interface for non-linear function optimization in Chapter 22.
• Python 2.7 support has been officially dropped, although most examples continue to work with 2.7. Do
not Python 2.7 for numerical code.
• Small typo fixes, thanks to Marton Huebler.
• Fixed direct download of FRED data due to API changes, thanks to Jesper Termansen.
• Thanks for Bill Tubbs for a detailed read and multiple typo reports.
• Updated to changes in line profiler (see Ch. 25)
• Updated deprecations in pandas.
• Removed hold from plotting chapter since this is no longer required.
• Thanks for Gen Li for multiple typo reports.
iv
Notes to the 3rd Edition
This edition includes the following changes from the second edition (August 2014):
• Python 3.5 is the default version of Python instead of 2.7. Python 3.5 (or newer) is well supported by
the Python packages required to analyze data and perform statistical analysis, and bring some new useful
features, such as a new operator for matrix multiplication (@).
• Removed distinction between integers and longs in built-in data types chapter. This distinction is only
relevant for Python 2.7.
• dot has been removed from most examples and replaced with @ to produce more readable code.
• Split Cython and Numba into separate chapters to highlight the improved capabilities of Numba.
• Verified all code working on current versions of core libraries using Python 3.5.
• pandas
• New chapter introducing statsmodels, a package that facilitates statistical analysis of data. statsmodels
includes regression analysis, Generalized Linear Models (GLM) and time-series analysis using ARIMA
models.
vi
Changes since the Second Edition
• Added diagnostic tools and a simple method to use external code in the Cython section.
• Added examples of joblib and IPython’s cluster to the chapter on running code in parallel.
• New chapter introducing object-oriented programming as a method to provide structure and organization
to related code.
• Added seaborn to the recommended package list, and have included it be default in the graphics chapter.
• Based on experience teaching Python to economics students, the recommended installation has been
simplified by removing the suggestion to use virtual environment. The discussion of virtual environments
as been moved to the appendix.
• Changed the Anaconda install to use both create and install, which shows how to install additional pack-
ages.
This edition includes the following changes from the first edition (March 2012):
• The preferred installation method is now Continuum Analytics’ Anaconda. Anaconda is a complete
scientific stack and is available for all major platforms.
• New chapter on pandas. pandas provides a simple but powerful tool to manage data and perform prelim-
inary analysis. It also greatly simplifies importing and exporting data.
• Numba provides just-in-time compilation for numeric Python code which often produces large perfor-
mance gains when pure NumPy solutions are not available (e.g. looping code).
• Numerous typos
1 Introduction 1
1.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Important Components of the Python Scientific Stack . . . . . . . . . . . . . . . . . . . . . 3
1.4 Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Using Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.A Additional Installation Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3 Arrays 29
3.1 Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.2 1-dimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.3 2-dimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.4 Multidimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.5 Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.6 Accessing Elements of an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.7 Slicing and Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.8 import and Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.9 Calling Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4 Basic Math 43
4.1 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.2 Broadcasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.3 Addition (+) and Subtraction (-) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.4 Multiplication (⁎) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.5 Matrix Multiplication (@) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.6 Array and Matrix Division (/) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
xii CONTENTS
6 Special Arrays 61
6.1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
7 Array Functions 63
7.1 Shape Information and Transformation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
7.2 Linear Algebra Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
7.3 Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
7.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
15 Graphics 125
15.1 seaborn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
15.2 2D Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
15.3 Advanced 2D Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
15.4 3D Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
15.5 General Plotting Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
15.6 Exporting Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
15.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
16 pandas 145
16.1 Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
16.2 Statistical Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
16.3 Time-series Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
16.4 Importing and Exporting Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
xiv CONTENTS
31 Examples 331
31.1 Estimating the Parameters of a GARCH Model . . . . . . . . . . . . . . . . . . . . . . . . 331
31.2 Estimating the Risk Premia using Fama-MacBeth Regressions . . . . . . . . . . . . . . . . 335
31.3 Estimating the Risk Premia using GMM . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
31.4 Outputting LATEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
Introduction
1.1 Background
These notes are designed for someone new to statistical computing wishing to develop a set of skills necessary
to perform original research using Python. They should also be useful for students, researchers or practition-
ers who require a versatile platform for econometrics, statistics or general numerical analysis (e.g. numeric
solutions to economic models or model simulation).
Python is a popular general–purpose programming language that is well suited to a wide range of problems.1
Recent developments have extended Python’s range of applicability to econometrics, statistics, and general
numerical analysis. Python – with the right set of add-ons – is comparable to domain-specific languages such
as R, MATLAB or Julia. If you are wondering whether you should bother with Python (or another language),
an incomplete list of considerations includes:
You might want to consider R if:
• You want to apply statistical methods. The statistics library of R is second to none, and R is clearly at the
forefront of new statistical algorithm development – meaning you are most likely to find that new(ish)
procedure in R.
• Free is important.
• Documentation and organization of modules are more important than the breadth of algorithms available.
• Performance is an important concern. MATLAB has optimizations, such as Just-in-Time (JIT) compila-
tion of loops, which is not automatically available in most other packages.
• You don’t mind learning enough Python to interface with Python packages. The Julia ecosystem is less
complete than Python and a bridge to Python is used to provide missing features.
1
According to the ranking on http://www.tiobe.com/tiobe-index/, Python is the 5th most popular language. http:
//langpop.corger.nl/ ranks Python as 4th or 5th .
2 Introduction
• You like to do most things yourself or you are on the bleeding edge and so existing libraries do not exist
with the features you require.
Having read the reasons to choose another package, you may wonder why you should consider Python.
• You need a language which can act as an end-to-end solution that allows access to web-based services,
database servers, data management and processing and statistical computation. Python can even be used
to write server-side apps such as a dynamic website (see e.g. http://stackoverflow.com), apps
for desktop-class operating systems with graphical user interfaces, or apps for tablets and phones apps
(iOS and Android).
• Data handling and manipulation – especially cleaning and reformatting – is an important concern. Python
is substantially more capable at data set construction than either R or MATLAB.
• Free is an important consideration – Python can be freely deployed, even to 100s of servers in on a
cloud-based cluster (e.g. Amazon Web Services, Google Compute or Azure).
1.2 Conventions
These notes will follow two conventions.
2. When a code block contains >>>, this indicates that the command is running an interactive IPython
session. Output will often appear after the console command, and will not be preceded by a command
indicator.
2
Python performance can be made arbitrarily close to C using a variety of methods, including numba (pure python), Cython
(C/Python creole language) or directly calling C code. Moreover, recent advances have substantially closed the gap with respect to
other Just-in-Time compiled languages such as MATLAB.
1.3 Important Components of the Python Scientific Stack 3
>>> x = 1.0
>>> x + 2
3.0
If the code block does not contain the console session indicator, the code contained in the block is
intended to be executed in a standalone Python file.
import numpy as np
x = np.array([1,2,3,4])
y = np.sum(x)
print(x)
print(y)
1.3.2 NumPy
NumPy provides a set of array data types which are essential for statistics, econometrics and data analysis.
1.3.3 SciPy
SciPy contains a large number of routines needed for analysis of data. The most important include a wide range
of random number generators, linear algebra routines, and optimizers. SciPy depends on NumPy.
1.3.6 pandas
pandas provides high-performance data structures and is essential when working with data.
1.3.7 statsmodels
statsmodels is pandas-aware and provides models used in the statistical analysis of data including linear regres-
sion, Generalized Linear Models (GLMs), and time-series models (e.g., ARIMA).
4 Introduction
1.4 Setup
The recommended method to install the Python scientific stack is to use Continuum Analytics’ Anaconda.
Appendix ?? describes a more complex installation procedure with instructions for directly installing Python
and the required modules when it is not possible to install Anaconda.
Windows
Installation on Windows requires downloading the installer and running. Anaconda comes in both Python
2.7 and 3.x flavors, and the latest Python 3.x is required. These instructions use ANACONDA to indicate
the Anaconda installation directory (e.g., the default is C:\Anaconda). Once the setup has completed, open a
PowerShell command prompt and run
cd ANACONDA\Scripts
conda init powershell
conda update conda
conda update anaconda
conda install html5lib seaborn jupyterlab
which will first ensure that Anaconda is up-to-date. conda install can be used later to install other packages
that may be of interest. Note that if Anaconda is installed into a directory other than the default, the full path
should not contain Unicode characters or spaces.
Notes
• Install for all users, which requires admin privileges. If these are not available, then choose the “Just
for me” option, but be aware of installing on a path that contains non-ASCII characters which can cause
issues.
1.5 Using Python 5
• Run conda init powershell to ensure that Anaconda commands can be run from the PowerShell
prompt.
• Register Anaconda as the system Python unless you have a specific reason not to (unlikely).
Linux and OS X
where x.y.z will depend on the version being installed and ISA will be either x86 or more likely x86_64.
Anaconda comes in both Python 2.7 and 3.x flavors, and the latest Python 3.x is required. The OS X installer is
available either in a GUI installed (pkg format) or as a bash installer which is installed in an identical manner to
the Linux installation. It is strongly recommended that the anaconda/bin is prepended to the path. This can be
performed in a session-by-session basis by entering conda init bash and then restarting your terminal. Note
that other shells such as zsh are also supported, and can be initialized by replacing bash with the name of your
preferred shell.
After installation completes, execute
conda update conda
conda update anaconda
conda install html5lib seaborn jupyterlab
which will first ensure that Anaconda is up-to-date and then install some optional modules. conda install
can be used later to install other packages that may be of interest.
Notes
All instructions for OS X and Linux assume that conda init bash has been run. If this is not the case, it is
necessary to run
cd ANACONDA
cd bin
• Tab completion - After entering 1 or more characters, pressing the tab button will bring up a list of
functions, packages, and variables which match the typed text. If the list of matches is large, pressing tab
again allows the arrow keys can be used to browse and select a completion.
• “Magic” function which make tasks such as navigating the local file system (using %cd ~/directory/
or just cd ~/directory/ assuming that %automagic is on) or running other Python programs (using
run program.py) simple. Entering %magic inside and IPython session will produce a detailed
description of the available functions. Alternatively, %lsmagic produces a succinct list of available
magic commands. The most useful magic functions are
– cd - change directory
– edit filename - launch an editor to edit filename
– ls or ls pattern - list the contents of a directory
– run filename - run the Python file filename
– timeit - time the execution of a piece of code or function
– history - view commands recently run. When used with the -l switch, the history of previous ses-
sions can be viewed (e.g., history -l 100 will show the most recent 100 commands irrespective
of whether they were entered in the current IPython session of a previous one).
• Integrated help - When using the QtConsole, calling a function provides a view of the top of the help
function. For example, entering mean( will produce a view of the top 20 lines of its help text.
• Inline figures - Both the QtConsole and the notebook can also display figure inline which produces a
tidy, self-contained environment. This can be enabled by entering %matplotlib inline in an IPython
session.
• The special variable _ contains the last result in the console, and so the most recent result can be saved
to a new variable using the syntax x = _.
• Support for profiles, which provide further customization of sessions.
This single line launcher can be saved as filename.command where filename is a meaningful name (e.g. IPython-
Terminal) to create a launcher on OS X by entering the command
chmod 755 /FULL/PATH/TO/filename.command
and then using the command as the Command in the dialog that appears.
1.5 Using Python 7
Windows (Anaconda)
To run IPython open PowerShell and enter IPython in the start menu. Starting IPython using the QtConsole
is similar and is simply called QtConsole in the start menu. Launching IPython from the start menu should
create a window similar to that in figure 1.1.
Next, run
in the terminal or command prompt to generate a file named jupyter_qtconsole_config.py. This file contains
settings that are useful for customizing the QtConsole window. A few recommended modifications are
c.ConsoleWidget.font_size = 12
c.ConsoleWidget.font_family = "Bitstream Vera Sans Mono"
c.JupyterWidget.syntax_style = "monokai"
These commands assume that the Bitstream Vera fonts have been locally installed, which are available from
http://ftp.gnome.org/pub/GNOME/sources/ttf-bitstream-vera/1.10/. Opening Qt-
Console should create a window similar to that in figure 1.2 (although the appearance might differ) if you
did not use the recommendation configuration.
work %run program.py or by directly launching the Python program using the standard interpreter using
python program.py. The advantage of using the IPython environment is that the variables used in the
program can be inspected after the program run has completed. Directly calling Python will run the program
and then terminate, and so it is necessary to output any important results to a file so that they can be viewed
later.3
To test that you can successfully execute a Python program, input the code in the block below into a text
file and save it as firstprogram.py.
# First Python program
import time
Once you have saved this file, open the console, navigate to the directory you saved the file and enter python
firstprogram.py. Finally, run the program in IPython by first launching IPython, and the using %cd to
change to the location of the program, and finally executing the program using %run firstprogram.py.
Figure 1.3: A successful test that matplotlib, IPython, NumPy and SciPy were all correctly installed.
backend is one of the available backends (e.g., qt5 or inline). Similarly %matplotlib backend can be used to
set just the backend without importing all of the modules and functions come with %pylab .
Most chapters assume that %pylab has been called so that functions provided by NumPy can be called
without explicitly importing them.
If everything was successfully installed, you should see something similar to figure 1.3.
Figure 1.4: The default IPython Notebook screen showing two notebooks.
To launch the jupyterlab server, open a command prompt or terminal and enter
jupyter lab
This command will start the server and open the default browser which should be a modern version of Chrome
(preferable), Chromium, Firefox or Edge. If the default browser is Safari or Internet Explorer, the URL can
be copied and pasted into Chrome. The first screen that appears will look similar to figure 1.4, except that the
list of notebooks will be empty. Clicking on New Notebook will create a new notebook, which, after a bit of
typing, can be transformed to resemble figure 1.5. Notebooks can be imported by dragging and dropping and
exported from the menu inside a notebook.
spyder
spyder is an IDE specialized for use in scientific applications of Python rather than for general purpose applica-
tion development. This is both an advantage and a disadvantage when compared to a full featured IDE such as
PyCharm or VS Code. The main advantage is that many powerful but complex features are not integrated into
Spyder, and so the learning curve is much shallower. The disadvantage is similar - in more complex projects,
or if developing something that is not straight scientific Python, Spyder is less capable. However, netting these
1.6 Exercises 11
Figure 1.5: A jupyterlab notebook showing formatted markdown, LATEX math and cells containing code.
two, Spyder is almost certainly the IDE to use when starting Python, and it is always relatively simple to migrate
to a sophisticated IDE if needed.
Spyder is started by entering spyder in the terminal or command prompt. A window similar to that in
figure 1.6 should appear. The main components are the editor (1), the object inspector (2), which dynamically
will show help for functions that are used in the editor, and the console (3). By default, Spyder opens a standard
Python console, although it also supports using the more powerful IPython console. The object inspector
window, by default, is grouped with a variable explorer, which shows the variables that are in memory and the
file explorer, which can be used to navigate the file system. The console is grouped with an IPython console
window (needs to be activated first using the Interpreters menu along the top edge), and the history log which
contains a list of commands executed. The buttons along the top edge facilitate saving code, running code and
debugging.
1.6 Exercises
1. Install Python.
2. Test the installation using the code in section 1.5.6.
3. Customize IPython QtConsole using a font or color scheme. More customization options can be found
by running ipython -h.
4. Explore tab completion in IPython by entering a<TAB> to see the list of functions which start with a and
are loaded by pylab. Next try i<TAB>, which will produce a list longer than the screen – press ESC to
exit the pager.
5. Launch IPython Notebook and run code in the testing section.
6. Open Spyder and explore its features.
12 Introduction
Python is whitespace sensitive and so indentation, either spaces or tabs, affects how Python interprets files. The
configuration files, e.g. ipython_config.py, are plain Python files and so are sensitive to whitespace. Introducing
white space before the start of a configuration option will produce an error, so ensure there is no whitespace
before active lines of a configuration.
Windows
Spaces in path
Unicode in path
Python does not always work well when a path contains Unicode characters, which might occur in a user
name. While this isn’t an issue for installing Python or Anaconda, it is an issue for IPython which looks
in c:\user\username\.ipython for configuration files. The solution is to define the HOME variable before
launching IPython to a path that has only ASCII characters.
mkdir c:\anaconda\ipython_config
set HOME=c:\anaconda\ipython_config
1.A Additional Installation Issues 13
c:\Anaconda\Scripts\activate econometrics
ipython profile create econometrics
ipython --profile=econometrics
The set HOME=c:\anaconda\ipython_config can point to any path with directories containing only ASCII
characters, and can also be added to any batch file to achieve the same effect.
OS X
Installing Anaconda to the root of the partition
If the user account used is running as root, then Anaconda may install to /anaconda and not ~/anaconda by
default. Best practice is not to run as root, although in principle this is not a problem, and /anaconda can be
used in place of ~/anaconda in any of the instructions.
Windows
Installation on Windows requires downloading the installer and running. These instructions use ANACONDA
to indicate the Anaconda installation directory (e.g. the default is C:\Anaconda). Once the setup has completed,
open a PowerShell prompt and run
cd ANACONDA\Scripts
conda init powershell
conda update conda
conda update anaconda
conda create -n econometrics qtconsole notebook matplotlib numpy pandas scipy spyder
statsmodels
conda install -n econometrics cython lxml nose numba numexpr pytables sphinx xlrd xlwt
html5lib seaborn
which will first ensure that Anaconda is up-to-date and then create a virtual environment named economet-
rics. Using a virtual environment is a best practice and is important since component updates can lead to
errors in otherwise working programs due to backward incompatible changes in a module. The long list of
modules in the conda create command includes the core modules. conda install contains the remain-
ing packages and is shown as an example of how to add packages to an existing virtual environment af-
ter it has been created. It is also possible to install all available Anaconda packages using the command
conda create -n econometrics anaconda.
The econometrics environment must be activated before use. This is accomplished by running
conda activate econometrics
from the command prompt, which prepends [econometrics] to the prompt as an indication that virtual environ-
ment is active. Activate the econometrics environment and then run
cd c:\
ipython
14 Introduction
which will open an IPython session using the newly created virtual environment.
Virtual environments can also be created using specific versions of packages using pinning. For example,
to create a virtual environment names old using Python 3.6 and NumPy 1.16,
which will install the requested versions of Python and NumPy as well as the latest version of SciPy and pandas
that are compatible with the pinned versions.
Linux and OS X
where x.y.z will depend on the version being installed and ISA will be either x86 or more likely x86_64. The
OS X installer is available either in a GUI installed (pkg format) or as a bash installer which is installed in an
identical manner to the Linux installation. After installation completes, change to the folder where Anaconda
installed (written here as ANACONDA, default ~/anaconda) and execute
cd ANACONDA
cd bin
./conda init bash
./conda update conda
./conda update anaconda
./conda create -n econometrics qtconsole notebook matplotlib numpy pandas scipy spyder
statsmodels
./conda install -n econometrics cython lxml nose numba numexpr pytables sphinx xlrd xlwt
html5lib seaborn
which will first ensure that Anaconda is up-to-date and then create a virtual environment named econometrics
with the required packages. conda create creates the environment and conda install installs additional
packages to the existing environment. conda install can be used later to install other packages that may be
of interest. To activate the newly created environment, run
conda activate econometrics
Before diving into Python for analyzing data or running Monte Carlos, it is necessary to understand some basic
concepts about the core Python data types. Unlike domain-specific languages such as MATLAB or R, where
the default data type has been chosen for numerical work, Python is a general purpose programming language
which is also well suited to data analysis, econometrics, and statistics. For example, the basic numeric type in
MATLAB is an array (using double precision, which is useful for floating point mathematics), while the basic
numeric data type in Python is a 1-dimensional scalar which may be either an integer or a double-precision
floating point, depending on the formatting of the number when input.
are all legal and distinct variable names. Note that names which begin or end with an underscore, while legal,
are not normally used since by convention these convey special meaning.1 Illegal names do not follow these
rules.
# Not allowed
x: = 1.0
1X = 1
X-1 = 1
for = 1
1
Variable names with a single leading underscore, for example _some_internal_value, indicate that the variable is for internal
use by a module or class. While indicated to be private, this variable will generally be accessible by calling code. Double leading
underscores, for example __some_private_value, indicate that a value is actually private and is not accessible. Variable names
with trailing underscores are used to avoid conflicts with reserved Python words such as class_ or lambda_. Double leading and
trailing underscores are reserved for “magic” variable (e.g. __init__) , and so should be avoided except when specifically accessing
a feature.
16 Built-in Data Types
The most important (scalar) data type for numerical analysis is the float. Unfortunately, not all non-complex
numeric data types are floats. To input a floating data type, it is necessary to include a . (period, dot) in the
expression. This example uses the function type() to determine the data type of a variable.
>>> x = 1
>>> type(x)
int
>>> x = 1.0
>>> type(x)
float
>>> x = float(1)
>>> type(x)
float
This example shows that using the expression that x = 1 produces an integer-valued variable while x = 1.0
produces a float-valued variable. Using integers can produce unexpected results and so it is important to include
“.0” when expecting a float.
Complex numbers are also important for numerical analysis. Complex numbers are created in Python using j
or the function complex().
>>> x = 1.0
>>> type(x)
float
>>> x = 1j
>>> type(x)
complex
>>> x = 2 + 3j
>>> x
(2+3j)
>>> x = complex(1)
>>> x
(1+0j)
Note that a+bj is the same as complex(a,b), while complex(a) is the same as a+0j.
2.2 Core Native Data Types 17
Floats use an approximation to represent numbers which may contain a decimal portion. The integer data
type stores numbers using an exact representation, so that no approximation is needed. The cost of the exact
representation is that the integer data type cannot express anything that isn’t an integer, rendering integers of
limited use in most numerical work.
Basic integers can be entered either by excluding the decimal (see float), or explicitly using the int()
function. The int() function can also be used to convert a float to an integer by round towards 0.
>>> x = 1
>>> type(x)
int
>>> x = 1.0
>>> type(x)
float
>>> x = int(x)
>>> type(x)
int
Python integers support have unlimited range since the amount of bits used to store an integer is dynamic.
>>> x = 1
>>> x
1
>>> type(x)
int
The Boolean data type is used to represent true and false, using the reserved keywords True and False. Boolean
variables are important for program flow control (see Chapter 12) and are typically created as a result of logical
operations (see Chapter 10), although they can be entered directly.
>>> x = True
>>> type(x)
bool
>>> x = bool(1)
>>> x
True
>>> x = bool(0)
>>> x
False
Non-zero, non-empty values generally evaluate to true when evaluated by bool(). Zero or empty values such
as bool(0), bool(0.0), bool(0.0j), bool(None), bool('') and bool([]) are all false.
18 Built-in Data Types
Substrings within a string can be accessed using slicing. Slicing uses [] to contain the indices of the characters
in a string, where the first index is 0, and the last is n − 1 (assuming the string has n letters). The following
table describes the types of slices which are available. The most useful are s[i], which will return the character
in position i, s[:i], which return the leading characters from positions 0 to i − 1, and s[i:] which returns the
trailing characters from positions i to n − 1. The table below provides a list of the types of slices which can
be used. The second column shows that slicing can use negative indices which essentially index the string
backward.
Slice Behavior
s[:] Entire string
s[i] Charactersi
s[i:] Charactersi, . . . , n − 1
s[:i] Characters0, . . . , i − 1
s[i: j ] Charactersi, . . . , j − 1
s[i: j :m] Charactersi,i + m,. . .i + m⌊ j−i−1
m ⌋
s[−i] Characters n − i
s[−i:] Charactersn − i, . . . , n − 1
s[:−i] Characters0, . . . , n − i − 1
s[− j :−i] Characters n − j, . . . , n − i − 1, − j < −i
s[− j :−i:m] Characters n − j,n − j + m,. . .,n − j + m⌊ j−i−1
m ⌋
>>> text[10]
'i'
>>> L = len(text)
>>> text[L] # Error
IndexError: string index out of range
>>> text[L-1]
2.2 Core Native Data Types 19
'.'
>>> text[:10]
'Python str'
>>> text[10:]
'ings are sliceable.'
Lists are a built-in container data type which hold other data. A list is a collection of other objects – floats,
integers, complex numbers, strings or even other lists. Lists are essential to Python programming and are used
to store collections of other values. For example, a list of floats can be used to express a vector (although the
NumPy data type array is better suited to working with collections of numeric values). Lists also support
slicing to retrieve one or more elements. Basic lists are constructed using square braces, [], and values are
separated using commas.
>>> x = []
>>> type(x)
builtins.list
>>> x=[1,2,3,4]
>>> x
[1,2,3,4]
These examples show that lists can be regular, nested and can contain any mix of data types including other
lists.
Lists, like strings, can be sliced. Slicing is similar, although lists can be sliced in more ways than strings. The
difference arises since lists can be multi-dimensional while strings are always 1×n. Basic list slicing is identical
to slicing strings, and operations such as x[:], x[1:], x[:1] and x[-3:] can all be used. To understand slicing,
assume x is a 1-dimensional list with n elements and i ≥ 0, j > 0, i < j,m ≥ 1. Python uses 0-based indices, and
so the n elements of x can be thought of as x0 , x1 , . . . , xn−1 .
20 Built-in Data Types
The default list slice uses a unit stride (step size of one) . It is possible to use other strides using a third
input in the slice so that the slice takes the form x[i:j:m] where i is the index to start, j is the index to end
(exclusive) and m is the stride length. For example x[::2] will select every second element of a list and is
equivalent to x[0:n:2] where n = len(x). The stride can also be negative which can be used to select the
elements of a list in reverse order. For example, x[::-1] will reverse a list and is equivalent to x[0:n:-1] .
Examples of accessing elements of 1-dimensional lists are presented below.
>>> x = [0,1,2,3,4,5,6,7,8,9]
>>> x[0]
0
>>> x[5]
5
>>> x[10] # Error
IndexError: list index out of range
>>> x[4:]
[4, 5, 6, 7, 8, 9]
>>> x[:4]
[0, 1, 2, 3]
>>> x[1:4]
[1, 2, 3]
>>> x[-0]
0
>>> x[-1]
9
>>> x[-10:-1]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
List can be multidimensional, and slicing can be done directly in higher dimensions. For simplicity, consider
slicing a 2-dimensional list x = [[1,2,3,4], [5,6,7,8]]. If single indexing is used, x[0] will return the
first (inner) list, and x[1] will return the second (inner) list. Since the list returned by x[0] is sliceable, the
inner list can be directly sliced using x[0][0] or x[0][1:4].
>>> x = [[1,2,3,4], [5,6,7,8]]
>>> x[0]
[1, 2, 3, 4]
>>> x[1]
[5, 6, 7, 8]
>>> x[0][0]
1
>>> x[0][1:4]
[2, 3, 4]
>>> x[1][-4:-1]
[5, 6, 7]
A number of functions are available for manipulating lists. The most useful are
2.2 Core Native Data Types 21
>>> x = [0,1,2,3,4,5,6,7,8,9]
>>> x.append(0)
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> len(x)
11
>>> x.extend([11,12,13])
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 11, 12, 13]
>>> x.pop(1)
1
>>> x
[0, 2, 3, 4, 5, 6, 7, 8, 9, 0, 11, 12, 13]
>>> x.remove(0)
>>> x
[2, 3, 4, 5, 6, 7, 8, 9, 0, 11, 12, 13]
Elements can also be deleted from lists using the keyword del in combination with a slice.
>>> x = [0,1,2,3,4,5,6,7,8,9]
>>> del x[0]
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x[:3]
[1, 2, 3]
However, if a tuple contains a mutable data type, for example a tuple that contains a list, the contents mutable
data type can be altered.
Tuples are constructed using parentheses (()) in place of the square brackets ([]) used to create lists. Tuples
can be sliced in an identical manner as lists. A list can be converted into a tuple using tuple() (Similarly, a
tuple can be converted to list using list()).
>>> x =(0,1,2,3,4,5,6,7,8,9)
>>> type(x)
tuple
>>> x[0]
0
>>> x[-10:-5]
(0, 1, 2, 3, 4)
>>> x = list(x)
>>> type(x)
list
>>> x = tuple(x)
>>> type(x)
tuple
>>> x= ([1,2],[3,4])
>>> x[0][1] = -10
>>> x # Contents can change, elements cannot
([1, -10], [3, 4])
Note that tuples containing a single element must contain a comma when created, so that x = (2,) is assign
a tuple to x, while x=(2) will assign 2 to x. The latter interprets the parentheses as if they are part of a
mathematical formula rather than being used to construct a tuple. x = tuple([2]) can also be used to create a
single element tuple. Lists do not have this issue since square brackets do not have this ambiguity.
>>> x =(2)
>>> type(x)
int
>>> x = (2,)
>>> type(x)
tuple
>>> x = tuple([2])
>>> type(x)
tuple
Tuples are immutable, and so only have the methods index and count, which behave in an identical manner to
their list counterparts.
(definitions). Dictionaries keys must be unique immutable data types (e.g. strings, the most common key, in-
tegers, or tuples containing immutable types), and values can contain any valid Python data type.3 Values are
accessed using keys.
>>> data = {'age': 34, 'children' : [1,2], 1: 'apple'}
>>> type(data)
dict
>>> data['age']
34
Values associated with an existing key can be updated by making an assignment to the key in the dictionary.
>>> data['age'] = 'xyz'
>>> data['age']
'xyz'
New key-value pairs can be added by defining a new key and assigning a value to it.
>>> data['name'] = 'abc'
>>> data
{1: 'apple', 'age': 'xyz', 'children': [1, 2], 'name': 'abc'}
A number of methods are available for manipulating sets. The most useful are
Function Method Description
set.add(x,element) x.add(element) Appends element to a set.
len(x) – Returns the number of elements in the set.
set.difference(x,set) x.difference(set) Returns the elements in x which are not in set.
set.intersection(x,set) x.intersection(set) Returns the elements of x which are also in set.
set.remove(x,element) x.remove(element) Removes element from the set.
set.union(x,set) x.union(set) Returns the set containing all elements of x and set.
The code below demonstrates the use of set. Note that 'MSFT' is repeated in the list used to initialize the
set, but only appears once in the set since all elements must be unique.
>>> x = set(['MSFT','GOOG','AAPL','HPQ','MSFT'])
>>> x
{'AAPL', 'GOOG', 'HPQ', 'MSFT'}
3
Formally dictionary keys must support the __hash__ function, equality comparison and it must be the case that different keys
have different hashes.
24 Built-in Data Types
>>> x.add('CSCO')
>>> x
{'AAPL', 'CSCO', 'GOOG', 'HPQ', 'MSFT'}
>>> x = x.union(y)
>>> x
{'AAPL', 'CSCO', 'GOOG', 'HPQ', 'MSFT', 'XOM'}
>>> x.remove('XOM')
{'AAPL', 'CSCO', 'GOOG', 'HPQ', 'MSFT'}
2.2.8 range
A range is most commonly encountered in a for loop. range(a,b,i) creates the sequences that follows
the pattern a, a + i, a + 2i, . . . , a + (m − 1)i where m = ⌈ b−a
i ⌉. In other words, it find all integers x starting with
a such a ≤ x < b and where two consecutive values are separated by i. range can be called with 1 or two
parameters – range(a,b) is the same as range(a,b,1) and range(b) is the same as range(0,b,1).
>>> x = range(10)
>>> type(x)
range
>>> print(x)
range(0, 10)
>>> list(x)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x = range(3,10)
>>> list(x)
[3, 4, 5, 6, 7, 8, 9]
>>> x = range(3,10,3)
>>> list(x)
[3, 6, 9]
range is not technically a list, which is why the statement print(x) returns range(0,10). Explicitly
converting with list produces a list which allows the values to be printed. range is technically an iterator
which does not actually require the storage space of a list.
container data types that extend the built-in data container data types. Two are particularly useful when working
with data: OrderedDict and defaultdict. Both of these extend the built-in dictionary dict with useful
features.
2.3.1 OrderedDict
When using a standard Python dict, items order is not guaranteed. OrderedDict addresses this frequent short-
coming by retaining a list of the keys inserted into the dictionary in the order in which they have been inserted.
The order is also preserved when deleting keys from an OrderedDict.
>>> from collections import OrderedDict
>>> od = OrderedDict()
>>> od['key1'] = 1
>>> od['key2'] = 'a'
>>> od['key3'] = 'alpha'
>>> plain = dict(od)
>>> print(list(od.keys()))
['key1', 'key2', 'key3']
>>> print(list(plain.keys()))
['key2', 'key1', 'key3']
This functionality is particularly useful when iterating over the keys in a dictionary since it guarantees a pre-
dictable order when accessing the keys (see Chapter 12). Recent versions of pandas also respect the order in an
OrderedDict when adding columns to a DataFrame (see Chapter 16).
2.3.2 defaultdict
By default attempting to access a key in a dictionary that does not exist will produce an error. There are
circumstances where this is undesirable, and when a key is encountered that doesn’t exist, a default value
should be added to the dictionary and returns. One particularly useful example of this behavior is when making
keyed lists – that is, grouping like elements according to a key in a list. If the key exists, the elements should
be appended to the existing list. If the key doesn’t exist, the key should be added and a new list containing the
new element should be inserted into the disctionary. defaultdict enables this exact scenario by accepting a
callable function as an argument. When a key is found, it behaved just like a standard dictionary. When a key
isn’t found, the output of the callable function is assigned to the key. This example uses list to add a new list
whenever a key is not found.
>>> d = {}
>>> d['one'].append('an item') # Error
KeyError: 'one'
The callable argument provided to defaultdict can be anything that is useful including other containers,
objects that will be initialized the first time called, or an anonymous function (i.e. a function defined using
lambda, see Section 18.4).
>>> id(y)
82970264
>>> x = 2.0
>>> id(x)
93850568
>>> id(y)
82970264
In the above example, the initial assignment of y = x produced two variables with the same ID. However, once
x was changed, its ID changed while the ID of y did not, indicating that the data in each variable was stored
in different locations. This behavior is both safe and efficient and is common to the basic Python immutable
types: int, float, complex, string, tuple, frozenset and range.
>>> x
[-10, 2, 3]
Slicing a list creates a copy of the list and any immutable types in the list – but not mutable elements in the list.
>>> x = [1, 2, 3]
>>> y = x[:]
>>> id(x)
86245960
>>> id(y)
86240776
4
The ID numbers on your system will likely differ from those in the code listing.
2.5 Exercises 27
To see that the inner lists are not copied, consider the behavior of changing one element in a nested list.
>>> x=[[0,1],[2,3]]
>>> y = x[:]
>>> y
[[0, 1], [2, 3]]
>>> id(x[0])
117011656
>>> id(y[0])
117011656
>>> x[0][0]
0.0
>>> id(x[0][0])
30390080
>>> id(y[0][0])
30390080
>>> x
[[-10.0, 1], [2, 3]]
When lists are nested or contain other mutable objects (which do not copy), slicing copies the outermost list to
a new ID, but the inner lists (or other objects) are still linked. In order to copy nested lists, it is necessary to
explicitly call deepcopy(), which is in the module copy.
>>> import copy as cp
>>> x=[[0,1],[2,3]]
>>> y = cp.deepcopy(x)
>>> y[0][0] = -10.0
>>> y
[[-10.0, 1], [2, 3]]
>>> x
[[0, 1], [2, 3]]
2.5 Exercises
1. Enter the following into Python, assigning each to a unique variable name:
(a) 4
(b) 3.1415
(c) 1.0
(d) 2+4j
(e) 'Hello'
(f) 'World'
2. What is the type of each variable? Use type if you aren’t sure.
Random documents with unrelated
content Scribd suggests to you:
lungamente resistere a quell'impeto, e cercarono scampo fuggendo
per le finestre.
Avendo i Francesi piantato delle batterie, i di cui fuochi riescivano
oltremodo funesti ai Romani, Garibaldi mise mano a una via
sotterranea, che li conducesse a quella volta con animo di farle colle
mine saltare in aria, lo che impedivagli il nemico di mandare ad
effetto, col rivolgere le acque dentro i lavori già avanzati, e de' quali
egli s'era avveduto.
La sera del 10 meditando un audacissimo colpo, Garibaldi riuniva
buon nerbo di truppe nella piazza di s. Pietro, e fattele disporre per
una incamiciata, le conduceva fuori dei muri con ordine di avanzarsi
in silenzio e di scagliarsi al convenuto segnale sull'accampamento
nemico, colla baionetta alla mano. Un inaspettato contrattempo
faceva sì che l'avanguardia sparato qualche tiro prima di giungere al
luogo, rendesse avvertiti i Francesi dell'imminente pericolo e non più
eseguibile il preparato assalto.
Tale stizza i Francesi aveano concepito contro Garibaldi, che
allorquando appresero com'egli soleva dall'alto del palazzo nella villa
Corsini osservar le loro operazioni e dirigere i movimenti delle truppe
romane, cominciarono a far piovere sulla malaugurata casa e
cannonate e bombe in tal copia, che non molto dopo dovette
Garibaldi abbandonarla perchè interamente guasta e prossima a
crollare. Di là egli trasportò il suo quartiere nella villa Spada,
egualmente esposta ai tiri del nemico.
Spuntava frattanto il giorno 12, in cui il generale Oudinot, terminati i
lavori d'approccio, trovavasi in posizione di poter bombardare Roma;
per cui rivolgendosi alle autorità scriveva: che ove dopo 12 ore
dall'intimazione la città non si fosse arresa, avrebbela attaccata di
viva forza: al che il Triumvirato fermo nell'onorevole proposito: «Non
tradiamo mai le nostre promesse, rispondeva: abbiamo promesso
difendere l'onore del paese e la bandiera della Repubblica:
manterremo la nostra promessa.» E dodici ore dopo ricominciava più
che mai furiosa la pugna. Videro in quel giorno i Francesi tali prove
di audacia, di valore e di militare scienza, che ne maravigliarono
spaventati. Garibaldi dà di quella tremenda giornata, ch'egli dirigeva
in persona, un saggio nella relazione che trasmise al governo; ivi è
detto: «Il furore de' nostri era al colmo, poichè mancando di
munizioni, questi prodi colsero le pietre, e con esse sconfissero il
nemico, gli tolsero le baionette dai fucili, e se ne servirono come
d'un arma terribile.»
In tutti quei giorni di lotta che seguirono dal 13 al 22, Garibaldi fu
visto dì e notte continuamente nei luoghi ove più ferveva la
battaglia, ed era più evidente il pericolo: la gente non sapeva
com'egli potesse tanto assiduamente mostrarsi dovunque le
emergenze di que' fortunosi momenti richiedessero la presenza d'un
uomo che valesse col consiglio e l'audacia a debitamente
provvedervi. Egli pareva non sentir mai il bisogno del riposo o quello
del cibo: sarebbesi detto che nel fuoco e nelle aspre fatiche della
guerra prendessero le di lui membra ristoro e forze novelle.
Occasione di nuovi ingenti sforzi e di valore disperato diede a
Garibaldi la notte in cui i nemici per la lenta ma sicura via delle opere
d'assedio, apparvero dentro i muri della città. Trovavasi egli in quel
momento in un posto di riserva e non appena giungevagli l'infausta
notizia, che in un colle truppe accorreva ad assalire colla baionetta
calata il nemico, che in fortissimo numero già s'era trincerato nelle
prese posizioni. Tornata vana tanta virtù, egli non si perdeva d'animo
per questo; chè all'alba con nuovo furore avventavasi risolutamente
un'altra volta all'ardimentoso cimento. Spinse i soldati a metter piede
perfin sui lavori del nemico, e con tal impeto e dispregio del pericolo
il fece, che erasi condotto tanto innanzi, che i nostri toccavano le
punte delle carabine ai soldati nemici, le quali sopravanzavano dalle
paralelle. Pure anco questo secondo tentativo rimaneva pur troppo
senza frutto dinanzi all'ostacolo dei trinceramenti, senza di cui il
nemico avrebbe dovuto come già altre volte ritirarsi sanguinoso e
disfatto. Erano quelli momenti supremi, e la posizione tristissima; e
nonostante il coraggio e il desiderio di nuovi paragoni col nemico in
tutti raddoppiavansi allo spettacolo sublime di Garibaldi e de' suoi. —
Roma riviveva ai tempi antichi.
Dalla nuova posizione in cui s'erano fortificati, i Francesi
bombardarono senza posa per molti giorni la città, e gravissimi danni
arrecarono agli antichi monumenti, che altri barbari e in più barbari
tempi avevano rispettato. E la ferocia di codesti stranieri che non
offesi, nè provocati eran calati in Italia senz'altra ragione che il
numero [12], senz'altro diritto che il sangue, veniva spinta a tal grado,
che i consoli delle estere nazioni, indignati a tanto strazio diressero
al generale francese una nota nella quale protestando contro «quel
modo d'attaccare che non solo minacciava le proprietà e le vite dei
neutri abitanti, ma anche quelle delle donne e dei fanciulli,
chiedevano in nome dell'umanità e delle nazioni civili che desistesse
dal bombardare più oltre, per salvare dalla distruzione la città
monumentale che è considerata come sotto la protezione morale di
tutti i paesi inciviliti del mondo.»
In onta alla voce che il mondo cristiano sollevava per bocca de' suoi
rappresentanti in Roma contro il vandalismo de' soldati di Francia, le
bombe continuarono senza ristarsi un momento a cadere sull'eroica
capitale d'Italia, e quanto più codesti pretesi liberatori dei popoli
vedevansi da un piccol numero d'uomini, nuovi quasi tutti alle armi e
privi dei potenti mezzi di guerra, di cui essi potevano disporre,
contrastato il trionfo e sovente ancora battuti, tanto maggiormente
s'imbestialivano, e il concetto furore con atti crudelissimi
disfogavano. Poco pareva a costoro il fulminare notte e giorno la
città coi mortai e co' cannoni, che anche spingevano all'assalto i
soverchianti battaglioni; ma a traverso le tenebre, colla mira
d'introdursi non visti e per sorpresa, dacchè l'approssimarsi di giorno
e venire a far prova faccia a faccia del proprio valore coi nostri
avevano vedute tornar loro sempre a danno e a vergogna. E tale
esito ebbe il colpo tentato la notte del 25, in cui da tutti i punti
assaliti vennero coraggiosamente respinti. Ripeterono l'assalto la
notte del 27 giovandosi d'una fitta nebbia e attaccando colla
baionetta; ma non valse loro nè la sorpresa nè la risolutezza
dell'assalto, chè un muro insuperabile di petti cittadini s'oppose a
contrastarli il passo. Ivi s'accese una mischia talmente accanita da
ambe le parti, che durante tutta la notte si continuò a combattere, il
micidiale incontro protraendosi fino a tardi nel giorno seguente.
Garibaldi sempre in mezzo al fuoco aizzava i compagni in quel furore
e gli esortava a non cedere, a tener fermo per l'onore italiano, e
accorrendo dovunque accresceva l'animo e la rabbia nei combattenti.
«Voi pugnate per la libertà e per l'onore d'Italia!» era il suo grido
prediletto di guerra, e a quel grido raddoppiavansi come per incanto
i colpi, sotto i quali cadevano i Francesi a mordere quel mal tocco
terreno. L'orribile pioggia di bombe e di granate accompagnava
incessantemente quegli attacchi alle fortificazioni, protetti pur anco
dalle artiglierie che avevano già grandemente dilatato la breccia.
Sulla quale avendo finalmente i nemici lanciato il dì 30 un numero
sterminato d'uomini, poterono collocare una batteria che rendeva
quasi del tutto vana ogni ulteriore resistenza. Nonostante male
sapendo Garibaldi comportare quel trionfo del nemico, che oramai
non era più in poter d'uomo contrastare lungamente, egli volle far
prova di scacciarlo dalle occupate posizioni, e riuscivagli il colpo;
senonchè rivennero poco dopo i Francesi alla pugna, e dovè
Garibaldi ritirarsi non senza però ritentare la fortuna che sorridevagli
per l'ultima volta, poichè avendo nuovamente respinto il nemico,
quando tutto già pareva perduto, questi rinforzatosi con nuove
truppe, rese impossibile ad umana forza ogni altro tentativo.
Questi rovesci ben lungi dal far desistere Garibaldi da ogni idea
d'ulteriore resistenza avevanlo sempre più confermato nel pensiero
di continuarsi ad opporre al Francese nella terza cinta protetta dalle
barricate al di qua del Tevere, e dopo aver fatto rovinare il ponte di
S. Angelo e quello di Sisto. Se il magnanimo proposito non fu
mandato ad effetto, debbesi attribuire a cause che da lui non
dipesero, e le quali la storia, fedele custode delle umane azioni, farà
note più tardi.
Non patendo a Garibaldi l'animo di cedere le gloriose armi allo
straniero invasore, risolveva uscire da Roma, ed avventurarsi a nuovi
pericoli; e fatto appello ai compagni con queste parole che
riportiamo fedelmente:
Soldati,
Ciò che io offro a quanti vogliono seguitarmi, eccolo: fame, freddo,
sole. Non paga, non caserme, non munizioni, ma avvisaglie
continue, marce forzate e fazioni alla baionetta. — Chi ama la patria
e la gloria mi seguiti.
Garibaldi.
radunò circa 3,000 uomini coi quali s'avviò alla volta di Tivoli, non
lontano forse dal credere che mantenendosi per qualche tempo nella
campagna, avrebbe potuto riunire a sè maggiori e considerevoli
elementi onde organizzare una lunga resistenza contro gli stranieri,
che da due parti diverse aveano invaso l'Italia, e i quali ad un tempo
s'affaccendavano ad inseguirlo, ben mostrando come degli Austriaci
chiamati barbari non fossero punto dissimili codesti altri calati di
Francia bestemmiando parole di libertà.
Non ignorava Garibaldi l'ardore con che ambedue si sarebbero
egualmente lanciati sulle di lui tracce, e perciò affine di meglio celar
loro e la propria situazione e le sue mire, aveva diviso in molti piccoli
drappelli le sue genti che spinse in direzioni diverse, mostrandosi
così nel tempo medesimo in disparatissimi punti. Per lo che i nemici,
francesi ed austriaci, quantunque in numero di gran lunga superiore,
mal sapendo ove rivolgersi per coglierlo, vedevansi obbligati ad
errare alla ventura, e con inutili marcie stancare i propri soldati, che
talora quando meno vi s'attendevano, sentivansi improvvisamente
colpiti dai tiri d'un nemico, di cui non trovavan più orma. Con questo
incessante avvicendarsi di marcie e di inseguimenti erasi condotto in
Toscana, coll'intendimento di tentare anche quelle popolazioni e
conoscerne l'animo. Apparve perciò nelle vicinanze di Montepulciano
verso il 10 di luglio, e sostò per prendervi riposo sull'alpestre monte
Fallonico, ove era impossibile al nemico l'avvicinarglisi. Entrò più
tardi in quella città, ove da un convento di frati furongli tratti alcuni
tiri di fucile; la qual cosa diede luogo a che Garibaldi ritenesse presso
di sè e conducesseli fuori, e il sottoprefetto ed alcuni preti di quel
paese, i quali rilasciò poi subito, senza ulteriormente occuparsi nè di
loro nè dei frati.
Accennando da Montepulciano alla volta d'Arezzo, stavano in
quest'ultima città e nella stessa Firenze in allarme gli uomini della
ristorazione, e l'italiana Arezzo vide le sue porte chiudersi
all'avvicinarsi di Garibaldi, come se uno straniero nemico o un
malfattore la minacciasse. Contro la quale condotta protestarono in
modo solenne il popolo e gli abitanti di quei dintorni, i quali
affrettaronsi numerosi a salutare i fratelli ed a recar loro il
bisognevole, onde potessero ristorarsi della fame e della sete patite
in que' lunghi travagli.
Erano in que' momenti le condizioni d'Italia tutta, e di Europa, poco
o nulla favorevoli alla causa della libertà, perciò i popoli non potendo
corrispondere agli eccitamenti di Garibaldi, stavano quieti, oppressi
dagli eserciti stranieri, accampati in gran numero nelle nostre
provincie. Fattosi persuaso Garibaldi della realtà dolorosa, per cui
doveva rimettere ai giorni avvenire il compimento del magnanimo
proposito rifaceva i passi, avviandosi verso l'Umbria. Anche durante
quella ritirata ebbe sempre ai fianchi l'austriaco, che inseguivalo
numeroso e senza prender mai posa. Marcie e contromarcie
precipitose e continue, riposi brevi, e conturbati sempre dal pensiero
d'un attacco imminente, vigilanza diligentissima, corse per luoghi
alpestri e tenuti per impraticabili; talora circondati dal nemico, che
stava per serrarli nella vasta cerchia, che facevasi ad ognora più
stretta, e con volte e rivolte sfuggirgli dalle mani, che già si
stendevano sopra di loro; tal altra lanciarsi arditamente tra mezzo
alle schiere nemiche, e transitare al punto bramato senza che
azzardassero offenderli. Per siffatte circostanze fu maravigliosa
quella ritirata verso gli stati romani, da dove Garibaldi risolveva
ricoverarsi finalmente in S. Marino, nella certezza di esservi ben
accolto.
La disciplina più rigorosa fu da Garibaldi fatta osservare dalle sue
truppe lungo questa escursione; a tale spinse lo scrupolo da quel
lato, che per lievi mancanze inflisse i più severi castighi. I luoghi per
cui transitò non ebbero che a lodarsi dell'ordine e del rispetto alle
persone e alle cose. Allorchè le vettovaglie mancavano, ei ricorreva
alle comuni che fornivangli l'occorrente, e giammai si fece lecito di
togliere da per se neppure lo strettamente necessario.
Molte volte i suoi uffiziali instarono presso di lui affine di indurlo a
battersi col nemico, ed egli consultando la difficile posizione in cui si
trovavano, e calcolato con maggior prudenza le cose, rifiutò
costantemente di farsi aggressore. Mancavangli i mezzi di trasporto
pei feriti, mancavagli un luogo sicuro ove depositarli: come mai
avrebbe egli potuto acconsentire in tanto critica condizione, che i di
lui compagni s'esponessero alle eventualità di una lotta, dalla quale
erasi convinto non poter più ricavare quei benefizi di che si era
lusingato dapprima?
Entrava quindi in S. Marino, ove il governo e gli abitanti facevangli
tutta quell'onorevole e lieta accoglienza che si doveva a fratelli. Quivi
chiamati a sè gli uffiziali, rendeva lor noto essere oramai inutile
continuare nell'intrapresa, e necessario quindi lo sciogliersi, e
provvedere ciascuno alla propria salute in quella terra amica.
Frattanto l'austriaco avea per mezzo del governo di S. Marino fatto
proporre a Garibaldi una capitolazione, colla quale era offerto libero
il campo per ritirarsi al proprio paese ad ognuno della sua colonna,
ed assicurato a lui un passaggio per l'America. Concertato col
reggente di S. Marino il modo di salvare i compagni, rifiutò per sè
ogni patto dell'austriaco, cui non volle umiliarsi.
Non rimanendo in Italia più altro campo ove si combattesse contro lo
straniero, tranne Venezia, ei concepì lo ardito divisamento di recarsi
a far le ultime prove nell'eroica città, che oramai sola sosteneva la
bandiera italiana colla guerra. Perciò accompagnato dalla moglie che
da Roma avevalo voluto seguire ad ogni costo, e da un centinaio
d'uomini i quali in onta a tutto non seppero risolversi ad
abbandonarlo, scese dalla montagna di S. Marino alle pianure del
Cesenatico, ove stavano a vigile guardia numerosi gli austriaci, più
che mai bramosi di averlo nelle mani. Mercè la scorta di generosi
patriotti di quei dintorni potè la piccola brigata passare non vista in
mezzo ai nemici, e giungere alla sponda senza verun ostacolo. Solo
non ebbe amica la fortuna quel santo martire, il quale smarritosi
nella corsa cadde in potere del nemico, e più tardi spirò in Bologna
rotto dai piombi tedeschi stromenti dell'ira clericale. Perdita che
lasciò un immenso dolore nell'animo di Garibaldi che nel P. Bassi
venerava il vero tipo dell'uomo di Dio.
Era questa la terza volta che egli veniva colpito nella parte più
sensibile del suo cuore dacchè aveva riveduto la patria. Fin dai primi
giorni del suo approdo in Genova la morte ponendo fine al martirio
di una troppo lunga infermità, avevagli rapito l'antico fratello d'armi,
il colonnello Anzani, al quale stringevalo stima ed affetto caldissimo.
Combattendo sotto le mura di Roma contro i Francesi erasi veduto
orbare d'un altro a lui estremamente caro per valore e per senno
militare, il colonnello Masina di Bologna. Pareva che un maligno
destino salvando a lui la vita da tanti e così fieri pericoli, volesse
fargliela misera ed insopportabile, accumulando sul di lui animo
dolori sopra dolori, che qui non ebbero ancor fine.
L'austriaco informato del rifiuto di Garibaldi per le condizioni
propostegli, emanò severissimi ordini contro chi avesse dato asilo a
lui e ai compagni, e come se l'atto già di per sè barbaro non fosse
bastante, un altro volle aggiungerne più barbaro ancora. Eragli noto
che la indivisibile compagna stavagli a fianco; — ed egli, il tedesco,
ricordavalo alle popolazioni, affinchè meglio fosse riconoscibile il
marito! e non si vergognava di avvertire inoltre come a più chiaro
indizio, che era la donna incinta da vari mesi. Lo stato dell'infelice
Anna, che per qualunque altro nemico sarebbe stato un titolo a
mitigare i feroci diritti della guerra, doveva servire invece
coll'austriaco a fare più desolata e lagrimevole la condizione di lei!
Tali sono gli uomini che pesano sulla nostra sventurata patria!
Ma il bando assassino dello straniero non metteva punto sgomento
nel cuore di quei generosi abitanti, poichè non solo ebbero i fuggitivi
fraterna accoglienza dovunque, ma trovarono sulla riva pronti i
pescherecci bragozzi che li accolsero e li condussero lontano.
Rivedendo il mare, e sentendolo fremere intorno a sè, quasi fosse la
cara voce d'un amico, esultava Garibaldi tra i buffi del vento che
venivano a scompigliarli sulla fronte i lunghi capegli; e navigando alla
volta di Venezia sentiva ognora più rinfrancarsi l'animo al pensare,
che tra non molto avrebbe potuto toccare la terra desiderata e forse
operare ancora qualche bel fatto che il suo nome non solo
illustrasse, ma, ciò che più stavagli a cuore, al nome italiano fosse
onorevole, e alla causa della libertà di giovamento. E l'ardore e la
straordinaria concitazione dell'animo suo ei comunicava ai compagni
stimolandoli colla seducente pittura de' nuovi pericoli e delle più
splendide glorie.
Così viaggiando tutta una notte erano sull'albeggiare pervenuti
all'altura di Comacchio, allorquando vedevansi sorgere dinanzi, e non
molto da loro discosto, i legni da guerra austriaci veglianti in quelle
acque, e senza alcun dubbio attendendoli. Appena scoperti furongli
rivolti sopra i cannoni, che incominciarono a bersagliarli fieramente;
in breve alcuni bragozzi andarono capovolti perendo miseramente le
persone, altri furono raggiunti e fatti prigioni; solo, per quanto ci
consta, pervenne Garibaldi a riguadagnare la costa col suo
palischermo. Forse alla sua rara abilità di marino, alla robustezza del
braccio, e al raro suo sangue freddo, ch'egli conserva sempre
inalterato anche ne' momenti d'estremo pericolo, o forse al volere
della Provvidenza che lo riserba al compimento di qualche alta
impresa, è dovuto se in tale emergenza potè sottrarsi agli
inseguitori.
Toccava finalmente la spiaggia; ma ivi la sua costanza ed il suo
valore dovevano trovarsi alla più tremenda prova, che mai padre e
marito possano sopportare. Tante corse affannose pe' monti tanti
giorni e notti senza prendere riposo, e lo sgomento continuo
nell'animo per la sorte del marito, e le privazioni d'ogni cosa al di lei
stato indispensabile, e l'incontro fatale sul mare, tutto aveva
contribuito a spossare le robuste forze della infelice sua donna, e a
condurla a termini di morte. Al toccare la riva appena rimaneva alla
sventurata un tenue alito di vita — Era quel luogo deserto; e nessun
soccorso poteva venirle apprestato. Più tardi apparve qualcheduno
cui Garibaldi mandò in fretta a Ravenna per un medico; ed inoltre
potè dalla pietà di quelle genti ottenere un biroccio, sul quale adagiò
la morente, che condusse nella casa d'un contadino, in una terra del
marchese Guiccioli, non molto lontana dal mare.
La povera famigliuola che l'abitava commossa a tanta sventura di
quegli sconosciuti offrì un letto per la donna moribonda —
Sventurato! appena Garibaldi ebbe tempo di coricarla, che già la
travagliata aveva finito di patire!
Quel colpo atterrò l'animo di colui che aveva tante volte nei suoi
giorni sentito senza punto commoversi ruggire intorno a sè la
desolazione e la morte — Chinò il capo come cedendo al peso di così
grande dolore; poi chiesto un bicchier d'acqua per mitigare l'arsura
che stringevalo alle fauci, ed alzato lo sguardo al cielo, quasi
invocandolo a testimonio di quanto pativa per la causa dell'umanità,
e dato un ultimo doloroso addio alla fredda spoglia della amata sua
donna, uscì frettoloso da quella casa e disparve.
Povera Anna! Ella che soleva con tanto amore visitare in America la
sepoltura d'una sua figliuoletta, che Dio le tolse, e volle tra i suoi
angeli, e con quell'affetto istesso con cui s'affaccendava a renderla
vaga e lieta d'ornamenti in vita, davasi continua cura perchè il
sepolcro ch'avevala accolta paresse men tristo, e desse
testimonianza d'un amore che durava oltre la fossa, povera Anna!
era gran mercè se la cristiana carità del buon contadino che avevala
ospitata, poteva dar riposo alle sue ossa in un campo ignorato,
senza che un segno le indicasse alla pietà de' suoi cari, o alla
reverenza di quanti hanno in pregio tanta virtù e tanto amore di
sposa!
Ma quelle ossa non poterono aver pace! chè
3. Vedi Corr. Liv., numeri citati, nei quali è diffusamente narrato questo
fatto.
4. Erano appunto sei mesi dacchè Garibaldi era stato dal governo incaricato
della spedizione al Salto.
10. Specie di mantello usato nelle campagne dei paesi del Rio de la Plata ed
altri luoghi dell'America meridionale.
13. Fu detto, che il Console francese in Tunisi d'accordo col sardo facesse
vive istanze presso il Bey, onde Garibaldi venisse respinto; e che il
secondo inviasse poi persona del Consolato a bordo del Tripoli con
incarico di far presente a Garibaldi che egli, il Console erasi adoperato
presso quel Governo affinchè gli accordasse la bramata ospitalità!
14. V. Mazzini, Italia del Popolo. — Vol. II, pag. 23 — gennaio 1850.
15. Nell'America del Nord quattro anni or sono vide la luce un romanzo
intitolato Dolores nel quale a Garibaldi è assegnata una nobile parte. —
Noi rammentiamo questo lavoro del nostro amico Harro Harring ad
encomio dell'autore e di Garibaldi.