Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Python for Finance
Python for Finance

Python for Finance: If your interest is finance and trading, then using Python to build a financial calculator makes absolute sense. As does this book which is a hands-on guide covering everything from option theory to time series.

eBook
$9.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Python for Finance

Chapter 2. Using Python as an Ordinary Calculator

In this chapter, we will learn some basic concepts and several frequently used built-in functions of Python, such as basic assignment, precision, addition, subtraction, division, power function, and square root function. In short, we demonstrate how to use Python as an ordinary calculator to solve many finance-related problems.

In this chapter, we will cover the following topics:

  • Assigning values to variables
  • Displaying the value of a variable
  • Exploring error messages
  • Understanding why we can't call a variable without assignment
  • Choosing meaningful variable names
  • Using dir() to find variables and functions
  • Deleting or unsigning a variable
  • Learning basic math operations—addition, subtraction, multiplication, and division
  • Learning about the power function, floor, and remainder
  • Choosing appropriate precision
  • Finding out more information about a specific built-in function
  • Importing the math module
  • The pi, e, log, and exponential functions...

Assigning values to variables

To assign a value to a variable is simple because unlike many other languages such as C++ or FORTRAN, in Python, we don't need to define a variable before we assign a value to it.

>>>pv=22
>>>pv+2
24

We could assign the same value to different variables simultaneously. In the following example, we assign 100 to the three variables x, y, and z at once:

>>>x=y=z=100

Displaying the value of a variable

To find out the value of a variable, just type its name as shown in the following code:

>>>pv=100
>>>pv
100
>>>R=0.1
>>>R
0.1

Error messages

Assuming that we issue the sqrt(3) command to estimate the square root of three, we would get the following error message:

>>>sqrt(3)
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    sqrt(3)
NameError: name 'sqrt' is not defined

The last line of the error message tells us that the sqrt() function is not defined. Later in the chapter, we learn that the sqrt() function is included in a module called math and that we have to load (import) the module before we can call the functions contained in it. A module is a package that contains a set of functions around a specific subject.

Can't call a variable without assignment

Assuming that we never assign a value to the abcde variable, after typing abcde, we would get the following error message:

>>>abcde
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    abcde
NameError: name 'abcde' is...

Choosing meaningful names

A perpetuity describes the situations where equivalent periodic cash flows happen in the future and last forever. For example, we receive $5 at the end of each year forever. A real-world example is the UK government bond, called consol, that pays fixed coupons. To estimate the present value of a perpetuity, we use the following formula if the first cash flow occurs at the end of the first period:

Choosing meaningful names

Here, PV is the present value, C is a perpetual periodic cash flow that happens at a fixed interval, and R is the periodic discount rate. Here C and R should be consistent. For example, if C is annual (monthly) cash flow, then R must be an annual (monthly) discount rate. This is true for other frequencies too. Assume that a constant annual cash flow is $10, with the first cash flow at the end of the first year, and that the annual discount rate is 10 percent. Compare the following two ways to name the C and R variables:

>>>x=10       # bad way for variable names...

Using dir() to find variables and functions

After assigning values to a few variables, we could use the dir() function to show their existence. In the following example, variables n, pv, and r are shown among other names. At the moment, just ignore the first five objects in the following code, which start and end with two underscores:

>>>pv=100
>>>r=0.1
>>>n=5
>>>dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', 'n', 'pv', 'r']

Deleting or unsigning a variable

Sometimes, when we write our programs, it might be a good idea to delete those variables that we no longer need. In this case, we could use the del() function to remove or unsign a variable. In the following example, we assign a value to rate, show its value, delete it, and type the variable name trying to retrieve its value again:

>>>rate=0.075
>>>rate
0.075

The value 0.075 seen...

Basic math operations – addition, subtraction, multiplication, and division

For basic math operations in Python, we use the conventional mathematical operators +, -, *, and /. These operators represent plus, minus, multiplication, and division operations respectively. All these operators are embedded in the following line of code:

>>>3.09+2.1*5.2-3/0.56
8.652857142857144

Although we use integer division less frequently in finance, a user might type the division sign twice (//) accidentally to get a weird result. The integer division is done with double slash //, which would return an integer value that is the largest integer than the final output. The result of 7 divided by 3 is 2.33, and 2 will be the largest integer smaller than 2.33. This example is shown in the following code:

>>>7/3
2.3333333333333335

For Python 2.x versions, 7/3 could be 2 instead of 2.333. Thus, we have to be careful. In order to avoid an integer division, we could use 7/2 or 7/2., that is...

The power function, floor, and remainder

For our FV=PV(1+R)^n, we use a power function. The floor function would give the largest integer smaller than the current value. The remainder is the value that remains after an integer division. Given a positive discount rate, the present value of a future cash flow is always smaller than its corresponding future value.

The following formula specifies the relationship between a present value and its future value:

The power function, floor, and remainder

In this formula, PV is the present value, FV is the future value, R is the cost of capital (discount rate) per period, and n is the number of periods. Assume that we would receive $100 payment in two years and that the annual discount rate is 10 percent. What is the equivalent value today that we are willing to accept?

>>>100/(1+0.1)**2
82.64462809917354

Here, ** is used to perform a power function. The % operator is used to calculate the remainder. Refer to the following example for the implementation of these operators:

>>...

Choosing appropriate precision

The default precision for Python has 16 decimal places as shown in the following example. This is good enough for most finance-related problems or research:

>>>7/3
2.3333333333333335

We could use the round() function to change the precision as follows:

>>>payment1=3/7
>>>payment1
0.42857142857142855
>>>payment2=round(y,5)
>>>payment2
0.42857

Assume that the units for both payment1 and payment2 are in millions. The difference could be huge after we apply the round() function with just two decimal places! If we use one dollar as our unit, the exact payment is $428,571. However, if we use millions instead and apply two decimal places, we end up with 430,000, which is shown in the following example. The difference is $1,429:

>>>payment1*10**6
428571.4285714285
>>>payment2=round(payment1,2)
>>>payment2
0.43
>>>payment2*10**6
430000.0

Finding out more information about a specific built-in function

To understand each math function, we apply the help() function, such as help(round), as shown in the following example:

>>>help(round)
Help on built-in function round in module builtins:
round(...)
    round(number[, ndigits]) -> number
Round a number to a given precision in decimal  
digits (default 0 digits).This returns an int when 
called with one argument, otherwise the same type as 
the number. ndigits may be negative.

Listing all built-in functions

To find out all built-in functions, we perform the following two-step approach. First, we issue dir() to find the default name that contains all default functions. When typing its name, be aware that there are two underscores before and another two underscores after the letters of builtins, that is, __builtins__:

>>>dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', 'x']...

Importing the math module

When learning finance with real-world data, we deal with many issues such as downloading data from Yahoo! finance, choosing an optimal portfolio, estimating volatility for individual stocks or for a portfolio, and constructing an efficient frontier. For each subject (topic), experts develop a specific module (package). To use them, we have to import them. For example, we can use import math to import all basic math functions. In the following codes, we calculate the square root of a value:

>>>import math
>>>math.sqrt(3)
1.732050807568772

To find out all functions contained in the math module, we call the dir() function again as follows:

>>>import math
>>>dir(math)
['__doc__', '__loader__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', &apos...

A few frequently used functions

There are several functions we are going to use quite frequently. In this section, we will discuss them briefly. The functions are print(), type(), upper(), strip(), and last expression _. We will also learn how to merge two string variables. The true power function pow() discussed earlier belongs to this category as well.

The print() function

Occasionally, we need to print something on screen. One way to do so is to apply the print() function as shown in the following example:

>>>import math            
>>>print('pi=',math.pi)
pi= 3.141592653589793

At this stage, a new user just applies this format without going into more detail about the print() function.

The type() function

In Python, the type() function can be used to find out the type of a variable as follows:

>>>pv=100.23
>>>type(pv)
<class 'float'>
>>>n=10
>>>type(n)
<class 'int'>
>>>

From these results...

Assigning values to variables


To assign a value to a variable is simple because unlike many other languages such as C++ or FORTRAN, in Python, we don't need to define a variable before we assign a value to it.

>>>pv=22
>>>pv+2
24

We could assign the same value to different variables simultaneously. In the following example, we assign 100 to the three variables x, y, and z at once:

>>>x=y=z=100

Displaying the value of a variable

To find out the value of a variable, just type its name as shown in the following code:

>>>pv=100
>>>pv
100
>>>R=0.1
>>>R
0.1

Error messages


Assuming that we issue the sqrt(3) command to estimate the square root of three, we would get the following error message:

>>>sqrt(3)
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    sqrt(3)
NameError: name 'sqrt' is not defined

The last line of the error message tells us that the sqrt() function is not defined. Later in the chapter, we learn that the sqrt() function is included in a module called math and that we have to load (import) the module before we can call the functions contained in it. A module is a package that contains a set of functions around a specific subject.

Can't call a variable without assignment

Assuming that we never assign a value to the abcde variable, after typing abcde, we would get the following error message:

>>>abcde
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    abcde
NameError: name 'abcde' is not defined
>>>

The last line tells...

Choosing meaningful names


A perpetuity describes the situations where equivalent periodic cash flows happen in the future and last forever. For example, we receive $5 at the end of each year forever. A real-world example is the UK government bond, called consol, that pays fixed coupons. To estimate the present value of a perpetuity, we use the following formula if the first cash flow occurs at the end of the first period:

Here, PV is the present value, C is a perpetual periodic cash flow that happens at a fixed interval, and R is the periodic discount rate. Here C and R should be consistent. For example, if C is annual (monthly) cash flow, then R must be an annual (monthly) discount rate. This is true for other frequencies too. Assume that a constant annual cash flow is $10, with the first cash flow at the end of the first year, and that the annual discount rate is 10 percent. Compare the following two ways to name the C and R variables:

>>>x=10       # bad way for variable names...
Left arrow icon Right arrow icon

Description

A hands-on guide with easy-to-follow examples to help you learn about option theory, quantitative finance, financial modeling, and time series using Python. Python for Finance is perfect for graduate students, practitioners, and application developers who wish to learn how to utilize Python to handle their financial needs. Basic knowledge of Python will be helpful but knowledge of programming is necessary.

What you will learn

  • Build a financial calculator based on Python
  • Learn how to price various types of options such as European, American, average, lookback, and barrier options
  • Write Python programs to download data from Yahoo! Finance
  • Estimate returns and convert daily returns into monthly or annual returns
  • Form an nstock portfolio and estimate its variancecovariance matrix
  • Estimate VaR (Value at Risk) for a stock or portfolio
  • Run CAPM (Capital Asset Pricing Model) and the FamaFrench 3factor model
  • Learn how to optimize a portfolio and draw an efficient frontier
  • Conduct various statistic tests such as Ttests, Ftests, and normality tests

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 02, 2014
Length: 408 pages
Edition : 1st
Language : English
ISBN-13 : 9781783284382
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Apr 02, 2014
Length: 408 pages
Edition : 1st
Language : English
ISBN-13 : 9781783284382
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 147.97
Introduction to R for Quantitative Finance
$43.99
Mastering Python for Finance
$54.99
Python for Finance
$48.99
Total $ 147.97 Stars icon
Banner background image

Table of Contents

13 Chapters
1. Introduction and Installation of Python Chevron down icon Chevron up icon
2. Using Python as an Ordinary Calculator Chevron down icon Chevron up icon
3. Using Python as a Financial Calculator Chevron down icon Chevron up icon
4. 13 Lines of Python to Price a Call Option Chevron down icon Chevron up icon
5. Introduction to Modules Chevron down icon Chevron up icon
6. Introduction to NumPy and SciPy Chevron down icon Chevron up icon
7. Visual Finance via Matplotlib Chevron down icon Chevron up icon
8. Statistical Analysis of Time Series Chevron down icon Chevron up icon
9. The Black-Scholes-Merton Option Model Chevron down icon Chevron up icon
10. Python Loops and Implied Volatility Chevron down icon Chevron up icon
11. Monte Carlo Simulation and Options Chevron down icon Chevron up icon
12. Volatility Measures 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.9
(22 Ratings)
5 star 50%
4 star 18.2%
3 star 13.6%
2 star 4.5%
1 star 13.6%
Filter icon Filter
Top Reviews

Filter reviews by




Amazon Customer Aug 26, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is a five star. It is a good book, it explains a lot about the concept in finance and python. If you are into learning python and finance, this is a good book for you. This book is more for beginners or intermediate. If you know a lot about about python or about finance, you should not get this book. I would recommend this book for finance major and people that want to learn about python. Since I have finish reading this book, I was able to learn how to code on my own. This book had help some of my finance classes.
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
Luis Cuellar Jun 02, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I am a systems engineer but have not program for a long time, and I am very interested in finance so I have been studying finance for the past months.For me this book is perfect, it teaches you python witch to me is a very powerful language witch you can learn fast and do very sophisticated things. and it teaches it with a very specific focus witch is applying it to Financial problems.The examples of the book are very well done, and helps ground your financial knowledge by programming the examples.The book takes you from installing the language to complicated graphical and mathematical solutions. The examples are well written and to the point.The only negative I find is the book assumes you know finance, so it is a programming book more that a financial book. But for me that was just fine.
Amazon Verified review Amazon
Red'D, Vijayawada Sep 16, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good book
Amazon Verified review Amazon
Nemo Aug 10, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
First of all this is not an in-depth python book or an in-depth finance book. So if you are looking for something with a strong technical bent on python or finance this is not it.It is, however, a great read if you are familiar with doing a lot of finance in another language like R and want to transition to python. With bloomberg providing a python API and C++ still being a real pain the rear this is a good way for more "analyst" types to become much more fluent and competent using a vastly more flexible language. It is not mega detailed - basically a "crash through" approach to doing a bit of python and doing it quickly. This is by no means a standalone solution to anything.The best use of this book is in conjunction with something more rigorous for finance and python. Aside from that it could be put to good use in an undergrad finance class so that instead of messing around in excel people actually learn a bit of code that they can build on later.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.