Python for Trading Series – Part 1

Python for Trading Series – Part 1

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

In trading, having coding skills gives you the ability to backtest your strategies, automate your trading or just make your trading more efficient in plenty of other 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. This post is part 1 of the series where I will teach you:

  1. How to install Python on your computer
  2. The basic building blocks of Python
  3. Conditional statements

Let’s begin.

Python Installation

There are many ways to install python on your computer but I recommend that you install the anaconda package from the anaconda website. This is a very popular package that consists of many data science and machine learning libraries for trading algorithms. Installing anaconda automatically installs python onto your computer. You will have to download the appropriate version of the package depending on your operating system specifications. It is easier to use the graphical installer. Once you have completed the download, you can just follow the instructions to complete the installation.

To write our code, we will need a text editor or an IDE (Integrated Development Environment) that supports python. For this, we will use Jupyter Notebook that comes with the anaconda installation. Jupyter Notebook is an open source application that lets you write your code in your web browser.

Now that we have our coding environment ready, let’s move on to writing our code.

Basic Building Blocks of Python

The most basic things you need to know in python are:

  1. constants
  2. variables
  3. calculations
  4. functions
  5. errors
  6. comments

Constants

A constant is a variable whose value cannot be changed. A constant can be a string, an integer or a float value.

An integer is a whole number that you can use to perform calculations.

Input:

print(2)

Output:

2

A float is a number with decimals that you can use to perform calculations.

Input:

print(2.5)

Output:

2.5

A string is a combination of characters wrapped around single or double quotes.

Input:

print(‘Hello World’)

Output:

Hello World

To find the type of the constant you are dealing with, you can use the inbuilt type function.

Input:

print(type(2))
print(type(2.5))
print(type(‘Hello World’))

Output:

<class ‘int’>

<class ‘float’>

<class ‘str’>

The type of a constant can be changed. For example, you can convert an integer to a float or a string value.

Input:

print(float(2))
print(str(2))
print(type(float(2)))
print(type(str(2)))

Output:

2.0

2

<class ‘float’>

<class ‘str’>

You can also convert a string containing only numbers to an integer or float value.

Input:

print(float(’55’))
print(int(’55’))

Output:

55.0

55

Variables

A variable is a named placeholder used to store data. This data can be an integer, string, list or an entire block of code. There are a few rules to remember while naming your variable:

  1. Variables can only start with alphabets or underscore ( _ )
  2. Variable names cannot have a blank space eg. “my variable”
  3. Variables cannot be reserved keywords in python like “print” or “type”
  4. Name your variables with something relevant to the data it stores so that it is easy to remember

While defining variables, the ‘=’ sign means assignment and not equality.

Input:

x = 55.8
stock_price = 100
my_sentence = ‘Hi there! How are you doing?’
algorithm = (2*5) + (3-1)

print(my_sentence)

Output:

Hi there! How are you doing?

Variables are UNIQUE. if you overwrite a variable, you delete the old data that was stored in the variable.

Input:

my_variable = ‘I am sad’
print(my_variable)
my_variable = ‘I am happy’
print(my_variable)

Output:

I am happy

Calculations

You can perform simple or complex calculations in python. Some operators you will use are + (addition), – (subtraction) , * (multiplication), / (division), ** (to the power of) and % (modulo, remainder)

Input:

print(5+3)
print(20 – 27)
print(3*4)
print(100/10)
print(5**2)
print(9%7)

Output:

8

-7

12

10.0

25

2

You can also assign these calculations to a variable and call them later.

Input:

calculation1 = 5+3
print(calculation1)

Output:

8

Variables can also be added to itself. It takes the former value of the variable, runs the calculation, and assigns the new answer to the variable.

Input:

count = 0
print(‘My count is ‘, count)
count = count + 3
print(‘My new count is ‘, count)

Output:

0

3

Functions

Python also has “functions”. Functions are pieces of code that do something. Some functions are built into Python. Some functions can be imported using libraries. Some functions you create yourself. You usually create functions for blocks of code that you will use repeatedly in your code so that you don’t have to explicitly type the code each time.

Some popular inbuilt python functions are ‘print’, ‘type’ & ‘len’. The ‘print’ function prints everything within brackets ‘( )’. The ‘type’ function returns the type of the variable or constant value within brackets ‘( )’ and the ‘len’ function gives the the number of characters in a string.

Input:

performance = 20
print(‘This trading algo returns’, performance, ‘percent per year’)

print(‘My name is ‘ + ‘Troy’)

print(type(50.8))

print(len(‘how many characters are in this sentence’))

Output:

This trading algo returns 20 percent per year

My name is Troy

<class ‘float’>

40

Errors

While coding, you will inevitably make some mistakes that lead to error messages. These errors are generally classified as syntax errors and logical errors.

Syntax errors arise when the syntax of your code is incorrect. For example,

Input:

print(‘The stock market today is up 2%

Output:

SyntaxError: EOL while scanning string literal

This can be easily fixed by looking up and correcting the syntax for the line of code where your error arises.

Logical errors arise during run time after clearing the syntax test. For example,

Input:

print(10/0)

Output:

ZeroDivisionError: division by zero

Comments

We use the HASH (#) sign to comment code. The purpose of commenting is to write notes for us coders to read. That way we know what we’re doing if we want to re-read our code in the future. Comments will not be executed when your computer runs the Python code. For example,

Input:

#Variable ‘moving_avg’ stores the value of moving average period

moving_avg = 50

print(moving_avg)

Output:

50


Now for the final part let’s look at conditional statements.

Conditional Statements

Conditional statements are lines of code which give multiple paths for the code to take depending on if the statement is TRUE or FALSE. Conditional statements are extremely important statements when using Python and coding for trading algorithms. Conditional statements generally have several “comparison operators” that return TRUE or FALSE as an answer. These operators are < (less than) , <= (less than or equal), == (equal), >= (greater than or equal), > (greater than), != (not equal).

Input:

print(5 > 10)

Output:

False

These comparison operators are used in IF statements. IF conditional statements have 3 parts: if, elif, and else. These IF statements run different pieces of code depending on whether the IF statement is TRUE or FALSE

Input:

x = 13

if x > 13:
print(‘X is greater than 13’)

elif x == 13:
print(‘X is exactly 13’)

else:
print(‘X is less than 13’)

Output:

X is exactly 13

*Notice the indentation after each of the conditional statements. This space is equal to 1 tab space or 4 ordinary blank spaces.

Multiple Conditions in a conditional Statement

You can have multiple conditions in a conditional statement. For example,

Input:

stock_valuation = ‘undervalued’
stock_type = ‘growth’
stock_price = 30

if (stock_valuation == ‘undervalued’) & (stock_type == ‘growth’) & (stock_price < 50):
print(‘Buy this stock’)

elif (stock_valuation == ‘overvalued’) & (stock_type == ‘value’) & (stock_price > 50):
print(‘Definitely do not buy this stock’)

else:
print(‘You may consider buying this stock’)

Output:

Buy this stock

Nested IF statements allow you to combine multiple IF statements to create multiple outcome paths. Nested IF statements execute the IF statements from left-hand side to right-hand side.

Input:

stock_trend = ‘up’
stock_price = 80

if stock_trend == ‘up’:

if stock_price > 100:
print(‘This is a nice momentum stock, but we do not buy expensive stocks’)

if stock_price <= 100:
print(‘This is a nice momentum stock that is cheap, so we will buy it’)

else:
print(‘we do not buy stocks that are trending down’)

Output:

This is a nice momentum stock that is cheap, so we will buy it

Try/Except

Try/Except statements are useful in that they allow us to run code WITHOUT the code breaking, even if the code has an error. TRY/EXCEPT basically means “try to run this code. If the code doesn’t work, DO NOT break. Skip that code and continue”. This is very useful for things like web scrapping when you don’t know exactly what type of data you’re running code on.

Let’s see a situation where the code might break and how to get over the problem using Try/Except statements. Let’s look at an old example we saw earlier. In that example, our variable x was the integer 13. For this example, we have changed it to a sentence.

Input:

x = ‘I am a sentence’

if x > 13:
print(‘X is greater than 13’)

elif x == 13:
print(‘X is exactly 13’)

else:
print(‘X is less than 13’)

Output:

TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’

The above code gives an error. So when this happens what you do is use TRY/EXCEPT. when the code within TRY breaks, the code will skip to EXCEPT, ignore the code that broke, and continue. That way you don’t get an error. For example,

Input:

try:
x = ‘I am a sentence’

if x > 13:
print(‘X is greater than 13’)

elif x == 13:
print(‘X is exactly 13’)

else:
print(‘X is less than 13’)

except:
print(‘The above code had an error, but we skipped it’)

Output:

The above code had an error, but we skipped it

This way when an error arises, we don’t get an error message but instead just perform the code under except and continue with the rest of the code.

Thank you for reading this tutorial. In part 2 of this Python For Trading series I will teach you how to use loops, collections, and functions. After that, I will share with you some trading algorithms!

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

Here is: Python for Trading Series – Part 2. 

Here is: Python for Trading Series – Part 3.