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: 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
$19.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.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. 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 : 9781783284375
Category :
Languages :
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 : Apr 02, 2014
Length: 408 pages
Edition : 1st
Language : English
ISBN-13 : 9781783284375
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
Python for Finance
$48.99
Mastering Python for Finance
$54.99
Introduction to R for Quantitative Finance
$43.99
Total $ 147.97 Stars icon

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

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.