Python for Algorithmic Trading: A to Z test.

I have tested in real-time the implementation coded with Python of a famous mathematical technics to predict market movement (Bollinger Band) to check the gap between theory and reality. And here is the result.

Sajid Lhessani
Nov 16, 2020 · 7 min read
Image for post
Image for post
Photo by Thomas Habr on Unsplash

Before to get started, let’s take a quick look at what we have covered during the previous articles. If you have not read my previous articles, you should cover these articles first. To get more details on how to draw Bollinger Bands and to get live market data with your API. (Link at the end of this article).

Otherwise, if you are too lazy to cover these articles, let’s have a short brief of what we covered along with these articles.

Let’s start by defining what the Bollinger Bands are.

Bollinger Bands?

Created in the early 80s and named after its developer (John Bollinger), Bollinger Bands represent a key technical trading tool for financial traders.

Image for post
Image for post
Source: Wikipedia

Bollinger Bands are an indicator of volatility. This mathematical technic uses the normal distribution to predict market movement. The normal distribution (also called gaussian) is a common feature of nature and psychology.

If we simplify the Bollinger Bands mathematical theory for the financial market:

There is 97.5% of chance that a share price is going up if we reach - 1.96 x σ(1), and conversely, there is 97.5% of chance for a share price to go down if we reached a value of + 1.96 x σ(1)

(1): σ is the standard deviation of the 20 latest periods.

As a result, Bollinger Bands can be used to draw a buying signal line which will be located at -1.96 times the standard deviation of the 20 last period, and a selling signal line which will be located at +1.96 times the standard deviation.

Let’s go back to our process.

As a scientist, I believe in what has been tested.

So, I chose to test these equations in live using my Jupyter Notebook for you.

To achieve this task I will use our best friend to automate this process, draw these lines, and give me the answer, I named: Python 3!

Happiness in the office after Python 3 have been chosen.

Are we gonna make or lose money, the result will be surprising, but I will not spoil you.

Let’s start the investigation.

We will divide the plan into 3 distinct steps.

First of all, we will query, live market data using Yahoo Finance API.

Second, define a period of time and create new columns for our calculated fields and update these values each minute.

Third, draw this graph live, and check if we can predict market movement.

If you are too impatient and want to know now how to implement this strategy, you can directly look at the recording at the end of this article. I recorded myself coding and gave extra information on the way to code. You can apply it at home.

Otherwise, let’s start the challenge.

Again, I will not go too much into details regarding the code and API; you can find more information on how to get live market reading the article below:

I will cover the process more superficially inside this article.

Import live Market Data

The first step will consist of importing the necessary packages. These packages are detailed in the article cited above.

So, you will start by importing your packages previously installed by using the following lines of code:

These lines of code above are querying Python to import the necessary libraries to develop our strategy.

Once we are set up, let’s pursue the next step.

Now that libraries are imported, we can import markets data.

II. Get connected to the market

Now that the different packages needed have been uploaded. We are going to use the SP500 to test our hypothesis.

So, we will call live market data using Yahoo Finance API.

For your information, Yahoo Finance API will need 3 mandatory arguments in this order:

  • Tickers (1)
  • Start date + End date or Period (2)
  • Interval (3)

For our case, the ticker(argument 1) will be SPY. Furthermore, we are going to choose for our test the last day period(argument 2) instead of defining a Start and End date. And we will set up an interval(argument 3) of 1 minute.

As a quick reminder, SP500's ticker is SPY.

To call your data, you will have to use the following structure:

Image for post
Image for post
Above described the structure to get market data which interest us.

Now that we have the structure let’s run the code.

Line of code to download market data

Below a sample of the output you should get:

Image for post
Image for post
Output sample

Now, that we have downloaded and stored our data, we can continue and define our moving average, buying & selling signals.

If you want more in-depth information, you can go across the link below:

III. Define our calculated fields

So, we will now create the following calculated field:

  • Moving Average
  • Upper Band
  • Lower Band

For the middle band, we will use the rolling function to get the mean value of the 21 latest periods. We are going to apply our strategy for the 21 last minutes, which means that we are going to calculate the mean for the 21 minutes before.

MiddleBand(t) = Average(Close(t-1 -> t-22))

For the Upper Band and Lower Band, we are going to use the rolling function as well, but instead of calculating the mean, we are going to calculate the standard deviation.

So, let’s code it on Python:

The code above, once executed will create 3 new columns to your dataframe

Now that you have defined your bands, 3 extra columns must have been created.

We can finally deploy our strategy and test it.

Draw this graph live

Now, the last step of our plan is to plot our data and check if we can predict market movement. I have recorded this part live in the video below:

This video is a step by step tutorial for coding the Bollinger Bands.

Boom! We made it.

If you cannot run the video, watch the result and hear my comments. Here a sample of what you should have once you have plotted your graph.

I have coloured in green in the graph below, the good prediction and black the wrong prediction.

Image for post
Image for post
Final output after running the Python code

Furthermore, I have uploaded the full Python script described in the video above and you can now develop it at home:

Full Python code

Final thought

Regarding the final output, using the Bollinger band theory, made us take the right choice 11 times and the wrong choice 3 times.

However, the wrong choice did not lead to making us lose money. It will just reduce our benefits (2 times sell too early, and 1 time buys too early).

Otherwise, the theory developed by John Bollinger in the 80’s looks to be up to date.

I have made a short calculation, and it would generate a 1.7% return in 3 hours if you would have used the Bollinger band for trading between 10 AM and 1 PM on this day, which surprises me.

What is even more interesting, I believe, it is to see how accurate it is. When the price was hitting an upper or lower band, the share price was correcting itself. You can see that on the graph above.

Overall, that has been an outstanding experience to compare theory vs reality.

Feel free to give feedback and ask if you have any question; I will do my best to help to unlock you.

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data…

By Analytics Vidhya

Latest news from Analytics Vidhya on our Hackathons and some of our best articles! Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Sajid Lhessani

Written by

Data scientist working in Banking and Capital market. London Based. Follow me on Youtube:

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data Science professionals. We are building the next-gen data science ecosystem

Sajid Lhessani

Written by

Data scientist working in Banking and Capital market. London Based. Follow me on Youtube:

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data Science professionals. We are building the next-gen data science ecosystem

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store