The Simplest Guide to Building a Stock Backtester in Python

Photo by on Unsplash

When it comes to stocks, a backtester is an essential tool.

Backtesting is a method of determining the practicality of a trading strategy by examining how it would perform using previous data. If you came up with a strategy, would you automatically trust it? No, you would want to test it, and historical data helps that. If backtesting proves to be effective, traders and analysts may be more willing to use it in the future.

Essentially, backtesting takes historical data and applies it to current data to predict how stocks would perform.

The main issue with backtesting is that it is a lot of work and takes a long to do manually, so that is why it would be smart to build one with Python. The strategy we will use is the moving averages strategy and implement that into our code. Let's Begin!

Build a Python Backtester

First, we will create a new file and import the necessary tools with the following segment.

Matplotlib is used to plot data visuall. Requests and JSON is used to pull data from the internet.

The next step is getting the input from the user. We would need to ask for what stock they are testing on(ask for ticker) and the initial investment(money you are putting into your system).

With the ticker name, we have to pull data from a website called CryptoCompareAPI by inserting the ticker name in the URL. We can use requests to pull all the content of the site, and then use JSON to pull just the data file.

With this information, we can test the data for the stock with the initial investment if after 5 days the end result is higher than the initial investment then it returns a don’t sell, if not then it returns a sell.

Now we have to do the part of the moving average of the program. We’ll store the initial investment in the initial variable and convert both the initial and cash variables to integers.

Next, we have to set up another empty variable, these are all used later.

The next we have to do is create a function called get_average which would add all the values for 5 days of closing investments and divide by 5. This is a simple average function used in basic maths. It can be done with a simple for loop.

Now, we start looping through the historical data (starting from the index 5 just to be the same as the averages). We can then calculate the five-day and three-day averages by passing the data points as an array, through our function.

Now we have to check if the 3-day average is greater than 5 because that means there is an upward trend, if there is an upward trend then we should buy stocks.

On the other hand, if the 3-day average is lesser than the 5 means there is a downward trend, and data won’t increase in price in the long term.

These two conditionals tell the user how much they should sell or buy, by taking the price of a stock and dividing it by half of the total cash (this is part of the moving averages strategy). It then multiplies the price by the amount of crypto you bought or sold and adds or subtracts it from the total. It prints this out at the end.

You can also get the portfolio value, which is your total cash, not just from that one investment. Then you can calculate the net value by subtracting portfolio value from the initial value.

These two X and Y values pull the time from the data, and y is the portfolio. We could plot this in a line graph with just 4 lines of code with matplotlib.

This code displays the following result.


You know now how to build a backtested for historical investment data for literally ANY stock. You also have the source code and explanation for it on this page as well as the full code right here. Good luck on all your coding and investing journey!

High School Student Interested in Programming and Tech:

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Let’s prepare for the jobs of tomorrow,

Top DevOps Trends For 2021

Datawave 2 playground

Trick/Hack to leverage GitHub Pages to simulate REST service (GET)

Battle of the Bases

ST bus will fill diesel at private pumps

I earned 20 cents on Medium yesterday.

Leased Line Providers in Lincolnshire #Lincolnshire

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
Ryan Rana

Ryan Rana

High School Student Interested in Programming and Tech:

More from Medium

ChakrDB: A Distributed RocksDB Born in the Cloud, Part 2

How Phuture works?– Non-technical overview & Guide to create your index.

2021 Goodyear Cotton Bowl Classic Preview: Should Alabama Be On Upset Alert vs. Cincinnati?

Supply ChainWhat the Fungible!! InfinitVerse takes the events forward in Metaverse in Dec 2021!