Quantitative Analysis, Risk Management, Modelling, Algo Trading, and Big Data Analysis

First Contact with Python

Python does miracles. Really. The more I’m diving into the abilities of this programming language the more I’m left speechless. This is this sort of feeling when you can swim among the sharks in the ocean and one day you jump off the plane and discover skydiving for the very first time. You are flying! Sounds appealing enough? Great! Welcome onboard!

py

Before the air of Python coding becomes your second nature you need to start your experience from the basics. They are no so exciting but provide you with the tastes and flavors of the language itself. With the promise to fly anywhere and a motivation standing behind that, it is solely up to you how hungry you are?! How hungry you are to leave your comfort zone of current programming habits in Java, C++ or Matlab, and step into the zone of magic?! This is a proving ground, the judgment day of your character: are you strong enough to accelerate your life, to gain a new skill and do something for yourself that a world will thank you tomorrow?!

Say “I’m ready!” if you are ready because I’m ready, then we shall begin…

Knockin’ on Heaven’s Door

If you went through my previous post on Python, you learned that there were at least two way of running Python in Unix/Linux/MacOSX environment: an interactive method (using Terminal) or active method (using IDLE; an integrated development environment). As for the latter solution, it utilizes a text editor to keep a track record of your codes while the former acts upon what you type and forgets about that as soon as you exit Python. To visualize that case simply see the clip at the end of this post where I provide you with a quick guide to running Python codes for the aforementioned two scenarios.

Now, we will compress our ability to assimilate Python’s fundamentals in the following couples of lines by referring to the codes executable from the text-editor level. Let the guys from MIT don’t think they are the best among the rest.

Python works in the mode of interpretation of every single line of code, line-by-line. It assumes you are responsible for what you wish to do or calculate so it doesn’t check your syntax in first place, flashes with red light and warns you. It trusts you! So as it goes through your code and finds typos, unknown variables, wrong types, or unrecognizable keywords or functions – then it will halt. Pretty fair deal. The rules of game are easy to grasp quickly. Let’s see the basics.

That’s one small Step for a Man, …

It is too much of a hassle to install and use Python as a simple calculator. But you can do it. Just add, subtract, do anything what follows the general rules of arithmetic:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Accelerated Python for Quants, Part 3
# (c) 2013 Pawel Lachowicz, QuantAtRisk.com
 
# Variables (BTW, the comments in Python start with #)
x=2
y=9
z=13.513
 
a=x+x
b=(x-3*x)*7.32+x/y
c=y**(1/x)
txt= 'is derived' # string
 
print a
print "b= ", b
print("The value of a equals to %g where c= %f %s" %(a,c,txt))

where we defined three variables $x, y$ and $z$, assigned to them some values and performed simple operations. The numerical results have been assigned to different three new variables, namely $a, b$, and $c$ with our intention to display them on the screen using the Python command of print. Running the code returns:

4
b=  -29.28
The value of a equals to 4 where c= 1.000000 is derived

Now, this is your first lesson on what Python assumes about your style of talking to it. It resembles a never-ending discussion among all women: does the size matter? I don’t know. Just ask them! But all I know is that for Python the type of the variables matters! Our variable of $x$ has been defined as an integer so $a=x+x=4$ as expected. But if you had tried to calculate:

print y/x

you would get:

4

instead of 4.5. To tell Python what you want, simply underline so-called float variable(s) to ensure that the calculation will be undertaken at the floating-point level by the processor. The following operations will force the outcome to be of the float type. Just check them out:

print 9.0/2.0, 9.0/2, 9./2, 9/2.0, 9/2.

Use the command of type to verify your variables anytime, for instance:

print(type(a))
print(type(b))
print(type(c))

should display

<type 'int'>
<type 'float'>
<type 'int'>

Note that in line #11 of the code, the value of $c$ is integer despite the fact we tried to perform the calculation of
$$
c=y^{1/x} \equiv \sqrt[x]{y} = 3 \ .
$$ Moreover, it failed delivering the outcome of $c=1$ which is far away for 3, right? This is all because of the difference in the type and you need to be aware of it while coding in Python. How to fix it? If your coding churns lots of variables of different kind you need to keep a track record of all of them and make sure what you want to obtain in result. A simple trick to force floating-point calculations is by the application of float() function acting directly on the variable or expression, for example:

c=float(y**(1/float(x)))
print c
c_i=int(c)
print c_i

will give you:

3.0
3

where the last line shows you how to convert, now correctly derived value of $c$ equal 3, into an integer type again assigned to a new variable of $c_i$.

Take also a closer look at lines #14-16 of the code where I showed you how differently you can display the information on the screen. The line #16 is an old-school way where you wish to display a sentence as a string-type variable which would contain some text of yours and include the values of two variables, namely $a$ and $c$. Inside the string you place a markers in form of %_ where %g, %f, and %s inform Python that it is asked to display the variables a,c, and txt in the integer, float, and string format, respectively.

Drilling the topic one level deeper, in your code you can check the type of any variable applying a conditional verification of some expressions which evaluate to the boolean type, i.e. True (=1) or False (=0).

So, here we go with a new Python structure of if-elif-else:

18
19
20
21
22
23
24
25
26
test=False
c=str(float(y**(1/float(x))))
if isinstance(c, int):
    print 'c is an integer>'
elif(isinstance(c,str)):
    print 'c is a string'
    Test=True
else:
    print "c is probably of a float-type"

resulting in:

c is a string

where we formulated a logical English-language-style question checking first condition whether $c$ was an integer, if not then checking another condition of $c$ being of the string type, and if that had failed the code would display an information letting us know about $c$ being probably a float. Easy? At least extremely intuitive.

Notice some differences in notations. Python accepts string encapsulated in single or double quotation. That’s very kind of it. Whatever you like, use in Python! Secondly, white spaces doesn’t matter unless they violate the syntax or spoil the output you desire to get. Thirdly, note colons (:) at the end of the line #20, #22, and #25. Forgetting about them is like jotting down an integral $\int x^2$ without $dx$ at the end. Fourthly, we can notice in line #19, #20, and #22 how we apply the idea of function acting on the inner arguments which are evaluated first in the order of nesting: inside$\rightarrow$out.

Lastly, in Python we use indentation for many cases or fixed language structures like if-elif-else mentioned above. The indentation means putting 4 white spaces (never Tab!) and then typing (see e.g. line #21). Why it so important? It occurs that some scientists conducted experiments on programmers and code developers and came out with a stunning result. When we code our brain is nearly blind to spaces or curly braces but it is sharp as a morning sun to the way how and where we nest some lines of code which of course improve the readability. The results were literally so mind-blowing that the guys who oversee Python evolution established (minimal) 4-space indentation as a standard. Keep that story in mind.

At the end we can make use of a variable test we made partially alive in the line #18. It appears again in the block of statements during if-elif-else conditional verification (line #24) and changes its value to True if $c$ appears to be of string type. Since in our code this is happening we send an additional order to Houston, where the guys from NASA commence the countdown of the Python rocket using another important language structure of while-loop as follows:

28
29
30
31
32
33
x = 10
while x >0:
    print(x)
    x-=1 
    if(x==0):
        print("Lift off!")

sending it into space when the launch status is reached:

10
9
8
7
6
5
4
3
2
1
Lift off!

 

HOMEWORK

Write a code in Python for the following problems making use of knowledge from this lesson. Submit your results as a comment to this post. Challenge your brain. We will accelerate next time, Warp 2, so buckle up!

(a) Given $|x-3|>21$ solve for $x$.
(b) The monthly rate of return for the cash investment option is $r=0.367$% and is fixed over the course of next 12 months. Find the annualized rate of return for that option. Hint- use the following formula in your code but applying while structure:
$$ R = \left[ \prod_{i=1}^{12} (1+r) \right] -1 $$
(c) A grandpa and a grandma are all together 147 days old. The grandpa is twice as old as the grandma when she was as old as the grandpa is right now. Find how old is grandpa and grandma today?

 

VIDEO

A quick guide to the methods how one can run the Python code in MacOS/Unix-like environment:

YouTube Preview Image

 

Contact Form Powered By : XYZScripts.com