Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Python for Finance
Python for Finance

Python for Finance: Apply powerful finance models and quantitative analysis with Python , Second Edition

eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Python for Finance

Chapter 2. Introduction to Python Modules

In this chapter, we will discuss the most important issues related to Python modules, which are packages written by experts or any individual to serve a special purpose. In this book, we will use about a dozen modules in total. Thus, knowledge related to modules is critical in our understanding of Python and its application to finance. In particular, in this chapter, we will cover the following topics:

  • Introduction to Python modules
  • Introduction to NumPy
  • Introduction to SciPy
  • Introduction to matplotlib
  • Introduction to statsmodels
  • Introduction to pandas
  • Python modules related to finance
  • Introduction to the pandas_reader module
  • Two financial calculators written in Python
  • How to install a Python module
  • Module dependency

What is a Python module?

A module is a package or group of programs that is written by an expert, user, or even a beginner who is usually very good in a specific area, to serve a specific purpose.

For example, a Python module called quant is for quantitative financial analysis. quant combines two modules of SciPy and DomainModel. The module contains a domain model that has exchanges, symbols, markets, and historical prices, among other things. Modules are very important in Python. In this book, we will discuss about a dozen modules implicitly or explicitly. In particular, we will explain five modules in detail: NumPy, SciPy, matplotlib, statsmodels, and Pandas.

Note

As of November 16, 2016, there are 92,872 Python modules (packages) with different areas available according to the Python Package Index.

For the financial and insurance industries, there are 384 modules currently available.

Assume that we want to estimate the square root of 3 by using the sqrt() function. However, after issuing...

Introduction to NumPy

In the following examples, the np.size() function from NumPy shows the number of data items of an array, and the np.std() function is used to calculate standard deviation:

>>>import numpy as np
>>>x= np.array([[1,2,3],[3,4,6]])     # 2 by 3 matrix
>>>np.size(x)                         # number of data items
6
>>>np.size(x,1)                       # show number of columns
3
>>>np.std(x)
1.5723301886761005
>>>np.std(x,1)
Array([ 0.81649658, 1.24721913]
>>>total=x.sum()                      # attention to the format
>>>z=np.random.rand(50)               #50 random obs from [0.0, 1)
>>>y=np.random.normal(size=100)       # from standard normal
>>>r=np.array(range(0,100),float)/100 # from 0, .01,to .99

Compared with a Python array, a NumPy array is a contiguous piece of memory that is passed directly to LAPACK, which is a software library for numerical linear algebra under the hood, so...

Introduction to SciPy

The following are a few examples based on the functions enclosed in the SciPy module. The sp.npv() function estimates the present values for a given set of cash flows with the first cash flow happening at time zero. The first input value is the discount rate, and the second input is an array of all cash flows.

The following is one example. Note that the sp.npv() function is different from the Excel npv() function. We will explain why this is so in Chapter 3, Time Value of Money:

>>>import scipy as sp
>>>cashflows=[-100,50,40,20,10,50]
>>>x=sp.npv(0.1,cashflows)
>>>round(x,2)
>>>31.41

The sp.pmt() function is used to answer the following question.

What is the monthly cash flow to pay off a mortgage of $250,000 over 30 years with an annual percentage rate (APR) of 4.5 percent, compounded monthly? The following code shows the answer:

>>>payment=sp.pmt(0.045/12,30*12,250000)
>>>round(payment,2)
-1266.71

Based on...

Introduction to matplotlib

Graphs and other visual representations have become more important in explaining many complex financial concepts, trading strategies, and formulas.

In this section, we discuss the matplotlib module, which is used to create various types of graphs. In addition, the module will be used intensively in Chapter 10, Options and Futures, when we discuss the famous Black-Scholes-Merton option model and various trading strategies. The matplotlib module is designed to produce publication-quality figures and graphs. The matplotlib module depends on NumPy and SciPy, which were discussed in the previous sections. To save generated graphs, there are several output formats available, such as PDF, Postscript, SVG, and PNG.

How to install matplotlib

If Python was installed by using the Anaconda super package, then matplotlib is preinstalled already. After launching Spyder, type the following line to test. If there is no error, it means that we have imported/uploaded the module successfully...

Introduction to statsmodels

statsmodels is a powerful Python package for many types of statistical analysis. Again, if Python was installed via Anaconda, then the module was installed at the same time. In statistics, ordinary least square (OLS) regression is a method for estimating the unknown parameters in a linear regression model. It minimizes the sum of squared vertical distances between the observed values and the values predicted by the linear approximation. The OLS method is used extensively in finance. Assume that we have the following equation, where y is an n by 1 vector (array), and x is an n by (m+1) matrix, a return matrix (n by m), plus a vector that contains 1 only. n is the number of observations, and m is the number of independent variables:

Introduction to statsmodels

In the following program, after generating the x and y vectors, we run an OLS regression (a linear regression). The x and y are artificial data. The last line prints the parameters only (the intercept is 1.28571420 and the slope is...

Introduction to pandas

The pandas module is a powerful tool used to process various types of data, including economics, financial, and accounting data. If Python was installed on your machine via Anaconda, then the pandas module was installed already. If you issue the following command without any error, it indicates that the pandas module was installed:

>>>import pandas as pd

In the following example, we generate two time series starting from January 1, 2013. The names of those two time series (columns) are A and B:

import numpy as np
import pandas as pd
dates=pd.date_range('20160101',periods=5)
np.random.seed(12345)
x=pd.DataFrame(np.random.rand(5,2),index=dates,columns=('A','B'))

First, we import both NumPy and pandas modules. The pd.date_range() function is used to generate an index array. The x variable is a pandas DataFrame with dates as its index. Later in this chapter, we will discuss the pd.DataFrame() function. The columns() function defines...

Python modules related to finance

Since this book is applying Python to finance, the modules (packages) related to finance will be our first priority.

The following table presents about a dozen Python modules or submodules related to finance:

Name

Description

Numpy.lib.financial

Many functions for corporate finance and financial management.

pandas_datareader

Retrieves data from Google, Yahoo! Finance, FRED, Fama-French factors.

googlefinance

Python module to get real-time (no delay) stock data from Google Finance API.

yahoo-finance

Python module to get stock data from Yahoo! Finance.

Python_finance

Download and analyze Yahoo! Finance data and develop trading strategies.

tstockquote

Retrieves stock quote data from Yahoo! Finance.

finance

Financial risk calculations. Optimized for ease of use through class construction and operator overload.

quant

Enterprise architecture for quantitative analysis in finance.

tradingmachine

A backtester for financial...

Introduction to the pandas_reader module

Via this module, users can download various economics and financial via Yahoo! Finance, Google Finance, Federal Reserve Economics Data (FRED), and Fama-French factors.

Assume that the pandas_reader module is installed. For detail on how to install this module, see the How to install a Python module section. First, let's look at the simplest example, just two lines to get IBM's trading data; see the following:

import pandas_datareader.data as web
df=web.get_data_google("ibm")

We could use a dot head and dot tail to show part of the results; see the following code:

>>> df.head()
>>> 
                  Open        High         Low       Close   Volume  
Date                                                                  
2010-01-04  131.179993  132.970001  130.850006  132.449997  6155300   
2010-01-05  131.679993  131.850006  130.100006  130.850006  6841400   
2010-01-06  130.679993  131.490005  129.809998  130.000000...

Two financial calculators

In the next chapter, many basic financial concepts and formulas will be introduced and discussed. Usually, when taking corporate finance or financial management, students rely on either Excel or a financial calculator to conduct their estimations. Since Python is the computational tool, a financial calculator written in Python would definitely enhance our understanding of both finance and Python.

Here is the first financial calculator, written in Python, from Numpy.lib.financial; see the following code:

>>> import numpy.lib.financial as fin
>>> dir(fin)
['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_convert_when', '_g_div_gp', '_rbl', '_when_to_num', 'absolute_import', 'division', 'fv', 'ipmt', 'irr&apos...

How to install a Python module

If Python was installed via Anaconda, there is a good chance that many of the modules discussed in this book have been installed together with Python. If Python was installed independently, users could use PyPi to install or update.

For example, we are interested in installing NumPy. On Windows, we have the following code:

python -m pip install -U pip numpy

If Python.exe is on the path, we could open a DOS window first, then issue the preceding line. If Python.exe is not on the path, we open a DOS window, then move to the location of the Python.exe file; for an example, see the following screenshot:

How to install a Python module

For a Mac, we have the following codes. Sometimes, after running the preceding command, you might receive the following message asking for an update of PiP:

How to install a Python module

The command line to update pip is given here:

python –m pip install –upgrade pip

See the result shown in the following screenshot:

How to install a Python module

To install NumPy independently, on Linux or OS X, we issue the following...

Module dependency

At the very beginning of this book, we argued that one of the advantages of using Python is that it is a rich source of hundreds of special packages called modules.

To avoid duplicated efforts and to save time in developing new modules, later modules choose to use functions developed on early modules; that is, they depend on early modules.

The advantage is obvious because developers can save lots of time and effort when building and testing a new module. However, one disadvantage is that installation becomes difficult.

There are two competing approaches:

  • The first approach is to bundle everything together and make sure that all parts play together nicely, thus avoiding the pain of installing n packages independently. This is wonderful, assuming that it works. A potential issue is that the updating of individual modules might not be reflected in the super package.
  • The second approach is to use minimal dependencies. It causes fewer headaches for the package maintainer, but for...

Exercises

  1. Do we have to install NumPy independently if our Python was installed via Anaconda?
  2. What are the advantages of using a super package to install many modules simultaneously?
  3. How do you find all the functions contained in NumPy or SciPy?
  4. How many ways are there to import a specific function contained in SciPy?
  5. What is wrong with the following operation?
    >>>x=[1,2,3]
    >>>x.sum()
  6. How can we print all the data items for a given array?
  7. What is wrong with the following lines of code?
    >>>import np
    >>>x=np.array([True,false,true,false],bool)
  8. Find out the meaning of skewtest included in the stats submodule (SciPy), and give an example of using this function.
  9. What is the difference between an arithmetic mean and a geometric mean?
  10. Debug the following lines of code, which are used to estimate a geometric mean for a given set of returns:
    >>>import scipy as sp
    >>>ret=np.array([0.05,0.11,-0.03])
    >>>pow(np.prod(ret+1),1/len(ret))-1
  11. Write a Python...

Summary

In this chapter, we have discussed one of the most important properties of Python: modules. A module is a package written by an expert or any individual to serve a special purpose. The knowledge related to modules is essential in our understanding of Python and its application to finance. In particular, we have introduced and discussed the most important modules, such as NumPy, SciPy, matplotlib, statsmodels, pandas, and pandas_reader. In addition, we have briefly mentioned module dependency and other issues. Two financial calculators written in Python were also presented. In Chapter 3, Time Value of Money, we will discuss many basic concepts associated with finance, such as the present value of one future cash flow, present value of perpetuity, present value of growing perpetuity, present value of annuity, and formulas related to future values. In addition, we will discuss definitions of Net Present Value (NPV), Internal Rate of Return (IRR), and Payback period. After that, several...

Left arrow icon Right arrow icon

Key benefits

  • Understand the fundamentals of Python data structures and work with time-series data
  • Implement key concepts in quantitative finance using popular Python libraries such as NumPy, SciPy, and matplotlib
  • A step-by-step tutorial packed with many Python programs that will help you learn how to apply Python to finance

Description

This book uses Python as its computational tool. Since Python is free, any school or organization can download and use it. This book is organized according to various finance subjects. In other words, the first edition focuses more on Python, while the second edition is truly trying to apply Python to finance. The book starts by explaining topics exclusively related to Python. Then we deal with critical parts of Python, explaining concepts such as time value of money stock and bond evaluations, capital asset pricing model, multi-factor models, time series analysis, portfolio theory, options and futures. This book will help us to learn or review the basics of quantitative finance and apply Python to solve various problems, such as estimating IBM’s market risk, running a Fama-French 3-factor, 5-factor, or Fama-French-Carhart 4 factor model, estimating the VaR of a 5-stock portfolio, estimating the optimal portfolio, and constructing the efficient frontier for a 20-stock portfolio with real-world stock, and with Monte Carlo Simulation. Later, we will also learn how to replicate the famous Black-Scholes-Merton option model and how to price exotic options such as the average price call option.

Who is this book for?

This book assumes that the readers have some basic knowledge related to Python. However, he/she has no knowledge of quantitative finance. In addition, he/she has no knowledge about financial data.

What you will learn

  • Become acquainted with Python in the first two chapters
  • Run CAPM, Fama-French 3-factor, and Fama-French-Carhart 4-factor models
  • Learn how to price a call, put, and several exotic options
  • Understand Monte Carlo simulation, how to write a Python program to
  • replicate the Black-Scholes-Merton options model, and how to price a few
  • exotic options
  • Understand the concept of volatility and how to test the hypothesis that
  • volatility changes over the years
  • Understand the ARCH and GARCH processes and how to write related
  • Python programs

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 30, 2017
Length: 586 pages
Edition : 2nd
Language : English
ISBN-13 : 9781787125698
Category :
Languages :
Concepts :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jun 30, 2017
Length: 586 pages
Edition : 2nd
Language : English
ISBN-13 : 9781787125698
Category :
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 142.97
Python Machine Learning, Second Edition
€32.99
Python for Finance
€41.99
Python: End-to-end Data Analysis
€67.99
Total 142.97 Stars icon

Table of Contents

16 Chapters
1. Python Basics Chevron down icon Chevron up icon
2. Introduction to Python Modules Chevron down icon Chevron up icon
3. Time Value of Money Chevron down icon Chevron up icon
4. Sources of Data Chevron down icon Chevron up icon
5. Bond and Stock Valuation Chevron down icon Chevron up icon
6. Capital Asset Pricing Model Chevron down icon Chevron up icon
7. Multifactor Models and Performance Measures Chevron down icon Chevron up icon
8. Time-Series Analysis Chevron down icon Chevron up icon
9. Portfolio Theory Chevron down icon Chevron up icon
10. Options and Futures Chevron down icon Chevron up icon
11. Value at Risk Chevron down icon Chevron up icon
12. Monte Carlo Simulation Chevron down icon Chevron up icon
13. Credit Risk Analysis Chevron down icon Chevron up icon
14. Exotic Options Chevron down icon Chevron up icon
15. Volatility, Implied Volatility, ARCH, and GARCH Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5
(33 Ratings)
5 star 39.4%
4 star 15.2%
3 star 15.2%
2 star 15.2%
1 star 15.2%
Filter icon Filter
Top Reviews

Filter reviews by




N/A Feb 07, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Excellent ! Can be a good textbook.
Feefo Verified review Feefo
Daniele Feb 12, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Amazing book with many interesting examples. Completely worth it
Amazon Verified review Amazon
Ana Isabel Bezerra Cavalcanti Oct 15, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Atendeu às minhas expectativas, em termos de pesquisas atuais e futuras.
Amazon Verified review Amazon
Jamie Jul 06, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I bought this eBook (with source code) from Packt. Great intro to Finance using Python. Chapter 10 and 12 are especially helpful as an addition to Hull's Options, Futures and Other Derivatives.
Amazon Verified review Amazon
Jaime May 21, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
For the past 3 years I have been investing part of my time directing and managing SW financial implementations in parallel of providing consulting services on several industries leveraging my expertise on Data Advisory specifically data management, governance and analytics/big data.During this tenure I have implemented diverse strategies to support my teams having a quick and solid ramp up getting hands on using in several cases Python in an specific framework either for data management or solving complex financial challenges on tricky calculations.I have found this book a great overview and hands on guidance to who is in the Python learning path and has realized to focus its functionality and powerful use on problem solving in the Finance arena or Analytics for example.Taking in count Python is powerful, flexible, ad easy to learn, the author provides a good and strong basis to go from the basic use of Python calculating net present value to more complex financial problems like valuations, pricing options, Monte Carlo series usage and regressions. Even also the author shares guidance to interact with public data sources such as Yahoo! Finance or Google Finance.Last but not least the content of this book will provide guidance to create very useful graphs by using Matlotlib in a clear way.Enjoy your reading!Note: If you have no Finance background, I recommend reading this book getting access to electronic or printed dictionary or related finance terms reference.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.