Reader small image

You're reading from  Python for Finance

Product typeBook
Published inApr 2014
Reading LevelBeginner
Publisher
ISBN-139781783284375
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Yuxing Yan
Yuxing Yan
author image
Yuxing Yan

Yuxing Yan graduated from McGill University with a PhD in finance. Over the years, he has been teaching various finance courses at eight universities: McGill University and Wilfrid Laurier University (in Canada), Nanyang Technological University (in Singapore), Loyola University of Maryland, UMUC, Hofstra University, University at Buffalo, and Canisius College (in the US). His research and teaching areas include: market microstructure, open-source finance and financial data analytics. He has 22 publications including papers published in the Journal of Accounting and Finance, Journal of Banking and Finance, Journal of Empirical Finance, Real Estate Review, Pacific Basin Finance Journal, Applied Financial Economics, and Annals of Operations Research. He is good at several computer languages, such as SAS, R, Python, Matlab, and C. His four books are related to applying two pieces of open-source software to finance: Python for Finance (2014), Python for Finance (2nd ed., expected 2017), Python for Finance (Chinese version, expected 2017), and Financial Modeling Using R (2016). In addition, he is an expert on data, especially on financial databases. From 2003 to 2010, he worked at Wharton School as a consultant, helping researchers with their programs and data issues. In 2007, he published a book titled Financial Databases (with S.W. Zhu). This book is written in Chinese. Currently, he is writing a new book called Financial Modeling Using Excel — in an R-Assisted Learning Environment. The phrase "R-Assisted" distinguishes it from other similar books related to Excel and financial modeling. New features include using a huge amount of public data related to economics, finance, and accounting; an efficient way to retrieve data: 3 seconds for each time series; a free financial calculator, showing 50 financial formulas instantly, 300 websites, 100 YouTube videos, 80 references, paperless for homework, midterms, and final exams; easy to extend for instructors; and especially, no need to learn R.
Read more about Yuxing Yan

Right arrow

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

  • Distinguishing between...

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...

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 in the previous code is an output, because the variable called rate was assigned...

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, at least...

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:

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']

Then, we type dir(__builtins__). The first and last couple...

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', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot'...

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 we know that pv is of the...

The tuple data type


For Python, a tuple is a data type or object. A tuple could contain multiple data types such as integer, float, string, and even another tuple. All data items are included in a pair of parentheses as shown in the following example:

>>>x=('John',21)
>>>x
('John', 21)

We can use the len() function to find out how many data items are included in each variable. Like C++, the subscript of a tuple starts from 0. If a tuple contains 10 data items, its subscript will start from 0 and end at 9:

>>>x=('John',21)
>>>len(x)
2
>>>x[0]
'John'
>>>type(x[1])
<class 'int'>

The following commands generate an empty tuple and one data item separately:

>>>z=()
>>>type(z)
<class 'tuple'>
>>>y=(1,)          # generate one item tuple
>>>type(y)
<class 'tuple'>
>>>x=(1)         # is x a tuple?

For a tuple, one of its most important features as shown in the following example, is...

Summary


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

For example, how to estimate the present value of one future cash flow, the future value of one cash flow today, the present value of a perpetuity, and the present value of a growing perpetuity. In addition, we discussed the dir(), type(), floor(), round(), and help() functions. We show how to get the list of all Python built-in functions and how to get help for a specific function.

Based on the understanding of the first two chapters, in the next chapter, Chapter 3, Using Python as a Financial Calculator, we plan to use Python as a financial calculator.

Exercises


1. What is the difference between showing the existence of our variables and showing their values?

2. How can you find out more information about a specific function, such as print()?

3. What is the definition of built-in functions?

4. What is a tuple?

5. How do we generate a one-item tuple? What is wrong with the following way to generate a one-item tuple?

>>>abc=("John")

6. Can we change the values of a tuple?

7. Is pow() a built-in function? How do we use it?

8. How do we find all built-in functions? How many built-in functions are present?

9. When we estimate the square root of three, which Python function should we use?

10. Assume that the present value of a perpetuity is $124 and the annual cash flow is $50; what is the corresponding discount rate?

11. Based on the solution of the previous question, what is the quarterly rate?

12. The growing perpetuity is defined as: the future cash flow is increased at a constant growth rate forever. We have the following formula:

Here PV...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Python for Finance
Published in: Apr 2014Publisher: ISBN-13: 9781783284375
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Yuxing Yan

Yuxing Yan graduated from McGill University with a PhD in finance. Over the years, he has been teaching various finance courses at eight universities: McGill University and Wilfrid Laurier University (in Canada), Nanyang Technological University (in Singapore), Loyola University of Maryland, UMUC, Hofstra University, University at Buffalo, and Canisius College (in the US). His research and teaching areas include: market microstructure, open-source finance and financial data analytics. He has 22 publications including papers published in the Journal of Accounting and Finance, Journal of Banking and Finance, Journal of Empirical Finance, Real Estate Review, Pacific Basin Finance Journal, Applied Financial Economics, and Annals of Operations Research. He is good at several computer languages, such as SAS, R, Python, Matlab, and C. His four books are related to applying two pieces of open-source software to finance: Python for Finance (2014), Python for Finance (2nd ed., expected 2017), Python for Finance (Chinese version, expected 2017), and Financial Modeling Using R (2016). In addition, he is an expert on data, especially on financial databases. From 2003 to 2010, he worked at Wharton School as a consultant, helping researchers with their programs and data issues. In 2007, he published a book titled Financial Databases (with S.W. Zhu). This book is written in Chinese. Currently, he is writing a new book called Financial Modeling Using Excel — in an R-Assisted Learning Environment. The phrase "R-Assisted" distinguishes it from other similar books related to Excel and financial modeling. New features include using a huge amount of public data related to economics, finance, and accounting; an efficient way to retrieve data: 3 seconds for each time series; a free financial calculator, showing 50 financial formulas instantly, 300 websites, 100 YouTube videos, 80 references, paperless for homework, midterms, and final exams; easy to extend for instructors; and especially, no need to learn R.
Read more about Yuxing Yan