How to code your own stock backtester [PART 0: Background]

Lucas Moyer
The Koi Life
Published in
2 min readSep 12, 2023

Let’s say you wanted to buy a stock whenever it was going up, simple enough?

Well how can we tell that the stock is going up? What’s up? What’s gucci? What’s what…

One way we could see how a stock is moving is to take the difference between a shorter moving average time span and a longer moving average time span.

Take a look at the MACD (Moving Average, Convergence/Divergence) indicator on MSFT stock from yahoo finance

The purple line is a 12 day moving average (12 MA) of the stock price while the orange line is a 26 day moving average (26 MA. The 26 MA is an average over a longer period of time, so it’s line is smoother and less reactive to small price jumps.

So if you took the difference between them AKA (12 MA — 26 MA), then what you have is an indicator. When the difference is positive, it could mean something like the stock price is going up. I say, “it could” because there are a lot of different ways to tell if a stock is going up and some indicators might give us different results.

Now, lets try to build a model of someone buying MSFT stock based on how positive the MACD difference was. If (12 MA — 26 MA) = 4, then let’s have it our model buy 4 shares of MSFT stock. If the difference is negative, let’s short the stock.

In the next series of articles, I will break down how I was able to implement this model in python and then compare if with the popular backtrader python testing framework, so we can get to the bottom of whether this trading strategy works or not.

You can expect:

  1. Data gathering and formatting
  2. Computing MACD into an indicator
  3. Using the data and indicator to perform a backtest
  4. Organizing the python code into a Stock class
  5. Comparing our backtester with backtrader’s
  6. Show how we can expand our Stock python class with more trading strategies and how to fit in a Portfolio class of multiple Stocks.

Thanks!

Bali Beaches

--

--

Lucas Moyer
The Koi Life

I strive to wake up everyday and pursue what I find most interesting. Writer for The Startup. Owner of The Koi Life medium.com/lucas-moyer