Python for Trading Series – Part 2

Python for Trading Series – Part 2

This guest post was written by Troy Bombardia. He shares free market research, data, and trading algorithms at Bull Markets.

Coding skills allows you to backtest your trading strategies, automate your trading, and make your trading more efficient in plenty of ways. In this Python For Trading series I will take you from knowing nothing about coding all the way to coding your own trading algorithms. You can find Part 1 of this series here. In Part 2 of this series I will teach you about:

  1. Loops
  2. Collections of data
  3. Functions

Let’s begin.

Loops

Python has an important feature called “loops”. Loops are extremely crucial when creating trading algorithms because they allow us to iterate and run through the same code, over and over again. There are 2 types of Loops in Python: “For” loops and “While” loops. Both are commonly used, but you’ll use FOR loops more than WHILE loops.

I’m going to show you simple examples to demonstrate what loops are and how to use them.

For Loop Syntax

The general syntax in a FOR loop looks like this:

Input:

for x in [1, 2, 3, 4, 5]:
print(x)

Output:

1

2

3

4

5

The “for” keyword indicates that this is a FOR loop. “x” is what you are iterating: this is called the “iteration variable”. You can name the “iteration variable” as anything you want. The list [1, 2, 3, 4, 5] is what we are iterating through. So the line of code “for x in [1, 2, 3, 4, 5]” means “for each item in [1, 2, 3, 4, 5]”, “print the item x”. Our output prints each of the items in the list. Here’s another example:

Input:

for stock in [‘apple’, ‘tesla’, ‘facebook’, ‘zoom’]:
print(stock, ‘is a tech stock’)

Output:

apple is a tech stock

tesla is a tech stock

facebook is a tech stock

zoom is a tech stock

Calculations in a For Loop

We can run calculations in our FOR loops. The following code may seem simple and not very useful, but it’s the building block for much more useful code later on.

Input:

count = 0
for x in [1, 2, 3, 4, 5, 6, 7]:
count = count + x
print(count)

print(‘We are finished counting’)

Output:

1

3

6

10

15

21

28

We are finished counting

Range function in a For Loop

Python has a RANGE function which you’ll often use in FOR loops. The range() function gives us a list of numbers, starting from a specified number, and incrementing by a certain number (default: 1), all the way to just before another specific number. This allows us to avoid typing out a very long list of numbers.

The general syntax of the range() function looks like this:

Input:

for x in range(1, 9):
print(x)

Output:

1

2

3

4

5

6

7

8

The above code is equivalent to the following code:

Input:

for x in [1, 2, 3, 4, 5, 6, 7, 8]:
print(x)

The range() function is very useful when you have a long list of numbers. It is much faster than typing out the numbers themselves.

Input:

count = 0

for x in range(0, 500):
count = count + x

print(‘The final count is’, count)

Output:

The final count is 124750

Combining For Loops with conditional statements

We can combine FOR loops with CONDITIONAL STATEMENTS (I touched on this topic in Part 1 of this series).

Input:

for number in range(0, 5):
if number < 3:
print(‘this number is less than 3’)
else:
print(number, ‘is >= 3’)

Output:

this number is less than 3

this number is less than 3

this number is less than 3

3 is >= 3

4 is >= 3

A Loop within a Loop

We can put a loop within a loop. For example,

Input:

for x in range(1, 3):
for y in range(4, 6):
print(‘the first number is’, x)
print(‘the second number is’, y)
print(‘—————-‘)

Output:

the first number is 1
the second number is 4
—————-
the first number is 1
the second number is 5
—————-
the first number is 2
the second number is 4
—————-
the first number is 2
the second number is 5
—————-

Break Statement

Python has a very useful statement called a “break” statement which stops the current loop that you’re in. You should use “break” when you want to stop the loop.

Input:

for n in range(0, 7):
if n <= 3:
print(n)
else:
break
print(‘We reached the number 3, so we are done’)

Output:

0

1

2

3

We reached the number 3, so we are done

As you can see, the code didn’t go through range(0, 7). It stopped at 3.

While Loop Syntax

Thusfar we have looked at FOR loops. FOR loops are what we call “definite” loops – the loop eventually ends. The 2nd kind of loop is a WHILE loop, which is an indefinite loop. We need to be careful with WHILE loops. If you don’t write code that will stop a WHILE loop, the WHILE loop will run indefinitely, potentially causing your computer to crash.

Here is an example of an infinite loop:

Input:

x = 3

while x > 2:
print(‘this number is greater than 2’)

Since x is ALWAYS greater than 2 (3 is always greater than 2), this WHILE loop will continue infinitely. It will never stop.

This is why WHILE loops need a way to end. They need a way to make the conditional statement “x > 2” FALSE. So here’s an example of ending the while loop:

Input:

x = 4

while x > 2:
print(x, ‘is greater than 2’)
x = x-1

Output:

4 is greater than 2

3 is greater than 2

Collections of Data

In this series, we’re going to look at 2 types of collections of data: LISTS and DICTIONARIES. Lists and dictionaries are very similar, but there are some important differences between them. Let’s start with lists.

Lists

A list is a collection of data. It allows us to put A LOT of data into a single variable. Here’s an example:

Input:

stocks_list = [‘apple’, ‘pfizer’]
amazon_stock_price = [‘3099’, ‘3099.4’, ‘3054’, ‘3033’, ‘3036’, ‘3015’, ‘2999.3’]

Each item in a list is called an “element”. List elements can be strings, integers, floats, other lists, etc.

Input:

for x in stocks_list:
print(x)
print(type(x))

Output:

apple

<class ‘str’>

pfizer

<class ‘str’>

Lists can also contain a combination of strings, integers, floats. This means that elements in a list don’t all have to be of the same type. For example,

Input:

combined_list = [‘jim’, 235, 10.4, [‘apple’, ‘pfizer’, ‘amazon’]]

As you can see in the example above, combined_list has strings, integers, floats, and a list within a list!

Here are some things you need to know about lists:

#1 lists are ordered

Elements in a list maintain their order. The elements in a list do not change order every time you call the list e.g.

Input:

stocks_list = [‘apple’, ‘pfizer’, ‘amazon’, ‘at&t’, ‘wal-mart’, ‘facebook’]

print(stocks_list)
print(stocks_list)
print(stocks_list)

Output:

[‘apple’, ‘pfizer’, ‘amazon’, ‘at&t’, ‘wal-mart’, ‘facebook’]

[‘apple’, ‘pfizer’, ‘amazon’, ‘at&t’, ‘wal-mart’, ‘facebook’]

[‘apple’, ‘pfizer’, ‘amazon’, ‘at&t’, ‘wal-mart’, ‘facebook’]

As you can see in the example above, the order of the elements in stocks_list remains unchanged, no matter how many times you print it.

#2 A list can be empty if you want it to be empty. Here’s how to create an empty list:

Input:

empty_list = []

print(empty_list)

Output:

[]

#3 Each list has a “length”. The number of elements in the list is the length. We can use the len() function to calculate the number of elements in a list:

Input:

stocks_list = [‘apple’, ‘pfizer’, ‘amazon’, ‘at&t’, ‘wal-mart’, ‘facebook’]
print(len(stocks_list))
print(‘There are’, len(stocks_list), ‘stocks in this list’)

Output:

6

There are 6 stocks in this list

#4 Lists have index operators. Since a list is ORDERED, we can use an index operator to “identify” and point to each element in the list. Index operators always start from 0. As you go from left to right in the list, the index operator increases by 1. The final element in a list (right-most element) is the length of the list or -1.

Input:

stocks_list = [‘apple’, ‘pfizer’, ‘amazon’]

print(stocks_list[0])
print(stocks_list[1])
print(stocks_list[2])

Output:

apple

pfizer

amazon

#5 Since lists have index operators, we can “slice” the list. “Slicing” a list means that we take a part of each list.

Input:

stocks_list = [‘apple’, ‘pfizer’, ‘amazon’, ‘at&t’, ‘wal-mart’, 543, ‘facebook’, ‘GE’, ‘JP Morgan’, ‘Bank of America’, 235, ‘Netflix’ ]

print(stocks_list[2:6])

Output:

[‘amazon’, ‘at&t’, ‘wal-mart’, 543]

#6 you can append to a list. Let’s say you have a list, and you want to add an additional element into that list, you can use the .append() function, which will “append” or add an element to the end of that list.

Input:

ceos = [‘Jeff Bezos’, ‘Andy Grove’, ‘Steve Jobs’, ‘Jamie Dimon’]

ceos.append(‘Troy Bombardia’)
print(ceos)

Output:

[‘Jeff Bezos’, ‘Andy Grove’, ‘Steve Jobs’, ‘Jamie Dimon’, ‘Troy Bombardia’]

#7 you can concatenate multiple lists. If you want to COMBINE multiple lists together, we say that you can “concatenate” multiple lists. In the example below, we have 2 lists, list1 & list2. Combined_list “concatenates” these 2 lists by putting a ‘+’ sign between them

Input:

list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8]

combined_list = list1 + list2
print(combined_list)

Output:

[1,2,3,4,5,6,7,8]

#8 lists are “MUTABLE”: you can change them. Since you can append elements to a list, combine lists, this means that lists are MUTABLE. “Mutable” means that a list can be changed. As a result, you can change specific elements in a list if you want to. We do this by using the index operator:

Input:

stocks = [‘google’, ‘twitter’, ‘uber’]

stocks[1] = ‘Facebook’

print(stocks)

Output:

[‘google’,Facebook’,’uber’]

Use Conditional Statements and Loops with Lists

We can use Conditional IF statements and LOOPS with lists:

Input:

names = [‘Sally’, ‘John’, ‘Tim’, ‘Jerry’]

for name in names:
print(name)

fund_manager_performance = [0.1, 0.02, -0.03, 0.17, 0.25, 0]

best_performance = 0

for performance in fund_manager_performance:
if performance > best_performance:
best_performance = performance
else:
continue

print(‘The best performance is’, best_performance)

Output:

Sally

John

Tim

Jerry

The best performance is 0.25

Dictionaries

Now that we’ve looked at lists, let’s look at dictionaries. Dictionaries are similar to lists in that they’re a collection of data. But unlike a list, a dictionary is UNORDERED, and stores data as “key”: “value” pairs.

  1. In a list, we used “index operators” to identify an element in a list.
  2. In a dictionary, we use a “key” to point to a specific “value”.

This means that you cant just put an element into a dictionary. You must insert it as a key-value pair. Here’s an example, we first create an empty list, and then insert key-value pairs into the dictionary:

Input:

wallet = {}

wallet[‘Sarah’] = 1500
wallet[‘Jim’] = 8000
wallet[‘Noah’] = 300
wallet[‘Sam’] = 500

print(wallet)

Output:

{‘Sarah’: 1500, ‘Jim’: 8000, ‘Noah’: 300, ‘Sam’: 500}

In the example above, the names Sarah, Jim, Noah, Sam are “keys”. The numbers 1500, 8000, 300, 500 are “values”. If we want to call a specific value, we must enter the key. There are no “index operators” to call since dictionaries are unordered!

Input:

print(wallet[‘Sarah’])
print(wallet[‘Noah’])

Output:

1500

300

Like lists, dictionaries can have strings, integers, floats, etc as values. Dictionaries have several key properties:

#1 a dictionary can be empty if you want it to be empty. This is how you create an empty dictionary:

Input:

empty_dictionary = {}
print(empty_dictionary)

Output:

{}

#2 each dictionary has a “length”. The length is the number of key-value pairs in the dictionary. We can use the len() function to calculate length:

Input:

stocks_price = {}

stocks_price[‘apple’] = 50
stocks_price[‘amazon’] = 3090
stocks_price[‘microsoft’] = 210

print(stocks_price)
print(len(stocks_price))

Output:

{‘apple’: 50, ‘amazon’: 3090, ‘microsoft’: 210}
3

#4 to add something to a dictionary, you need to insert a new key-value pair:

Input:

stocks_price = {}

stocks_price[‘apple’] = 50
stocks_price[‘amazon’] = 3090
stocks_price[‘microsoft’] = 210

#if you want to add something to a dictionary:

stocks_price[‘walmart’] = 150
print(stocks_price)

Output:

{‘apple’: 50, ‘amazon’: 3090, ‘microsoft’: 210, ‘walmart’: 150}

#5 like a list, python dictionaries are “mutable”, meaning that they can be changed. You can also update the values in a dictionary’s key-value pair:

Input:

stocks_price[‘apple’] = stocks_price[‘apple’] + 10
print(stocks_price)

Output:

{‘apple’: 60, ‘amazon’: 3090, ‘microsoft’: 210, ‘walmart’: 150}

Functions

Python allows you to have blocks of code called “functions” that run when you call the function. Functions are useful because they allow you to avoid repetition. Here’s a very simple example to illustrate: Let’s say we want to know the number of items in a list, you can find this out using the following code:

Input:

companies = [‘apple’, ‘google’, ‘dell’, ‘home depot’, ‘walgreens’, ‘exxon mobil’]

count = 0

for x in companies:
count = count + 1

print(count)

Output:

6

Alternatively, we can use the len() function to make this code more concise:

Input:

companies = [‘apple’, ‘google’, ‘dell’, ‘home depot’, ‘walgreens’, ‘exxon mobil’]
print(len(companies))

Output:

6

Syntax for Functions

The general syntax for functions is as follows: function name, brackets, function arguments. For example, print(‘hi there’): print = function name, () = brackets, ‘hi there’ = function arguments

There are 3 types of functions: python’s built-in functions, functions that you can build yourself, and imported functions from libraries.

Python has a few built-in functions. To see the list of built-in functions:

Input:

import builtins
dir(builtins)

This prints out all the python builtin functions.

Built-in Functions

We’re not going to go through all the built-in functions, but we’ll just cover a few of the ones that are more frequently used in finance.

sum() function adds up a bunch of numbers:

Input:

list_of_numbers = [23, 1, 6, 34, 6, 12, 5, 6]

print(sum(list_of_numbers))

Output:

93

max() function finds the largest number in a set of numbers:

Input:

list_of_numbers = [23, 1, 6, 34, 6, 12, 5, 6]

print(max(list_of_numbers))

Output:

34

min() function finds the minimum number in a set of numbers.

Input:

list_of_numbers = [23, 1, 6, 34, 6, 12, 5, 6]

print(min(list_of_numbers))

Output:

1

Importing Libraries

You can also create your own functions. We’ll cover that in a later part of the series. For now, it’s easier to know how to use built-in functions and functions from libraries. Python has “libraries”, which are collections of code that you can import into your code. In other words, you can import these pre-built functions and use these functions in your own code. It’s faster than creating your own functions! 2 of the most common libraries we’ll use are Numpy and Pandas. These are 2 of the most widely used python libraries in data science. They allow us to easily do many types of calculations (e.g. calculate mean, standard deviation, matrix calculations) with a simple pre-built function, instead of writing our own code from scratch! Whenever you want to use a library in your own code, you must first “import” it:

Input:

import numpy as np
import pandas as pd

Imported Functions

Once you’ve imported these 2 libraries, you can use all the functions that they offer. For example, you can use the np.mean() function (from numpy) to calculate the mean of a list of numbers:

Input:

list_of_numbers = [23, 1, 6, 34, 6, 12, 5, 6]
print(np.mean(list_of_numbers))

Output:

11.625

If you didn’t use functions, this code would become a lot longer:

Input:

total = 0
list_of_numbers = [23, 1, 6, 34, 6, 12, 5, 6]

for x in list_of_numbers:
total = total+x

number_of_numbers = len(list_of_numbers)

print(total/number_of_numbers)

Output:

11.625

Thank you for reading this tutorial. In part 3 of this Python For Trading series I will share with you how to code your own Trading Algorithms!

You can follow Troy Bombardia on Twitter @BullMarketsco. or at his website www.bullmarkets.co.

Here is: Python for Trading Series – Part 1 if you missed it.

Here is: Python for Trading Series – Part 3 if you missed it.