The Simplest Guide to Building a Stock Backtester in Python

Ryan Rana
4 min readAug 11, 2021
Photo by CardMapr.nl 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.

Conclusion

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!

--

--