Wednesday, July 16, 2014

Simple backtesting module

My search of an ideal backtesting tool (my definition of 'ideal' is described in the earlier 'Backtesting dilemmas' posts) did not result in something that I could use right away. However, reviewing the available options helped me to understand better what I really want. Of the options I've looked at, pybacktest was the one I liked most because of its simplicity and speed. After going through the source code,  I've got some ideas to make it simpler and a bit more elegant. From there, it was only a small step to writing my own backtester, which is now available in the TradingWithPython library.

I have chosen an approach where the backtester contains functionality which all trading strategies share and that often gets copy-pasted. Things like calculating positions and pnl, performance metrics and making plots.

Strategy specific functionality, like determining entry and exit points should be done outside of the backtester. A typical workflow would be:
find entry and exits -> calculate pnl and make plots with backtester -> post-process strategy data

At this moment the module is very minimal (take a look at the source here), but in the future I plan on adding profit and stop-loss exits and multi-asset portfolios.

Usage of the backtesting module is shown in this example notebook


  1. Hey,
    Nice blog! Got a quick question: can the backtester deal with multiple positions in at the same time?

    I.e. go long at time=t and go long at time=t+n and decide only close the first long, but keep the second one open at time=t+m (n<m)?


    1. Not like that. However, you can create multiple Backtest classes that together do what you need

  2. Hi,

    is the tradeBracket() function useful for backtesting with take-profit and stop-loss exits? Could you add an example for tradeBracket() usage?

    Thank you.

  3. Did you find any good portfolio back testing tools?

    1. I've taken a look at some other (new) tools like backtrader, but I still use my own simple backtester.