Don't Miss
Home » Trading Evolved

Trading Evolved

Order now!

More than any other technological change, the rise of Python in the past years has dramatically leveled the playing field in systematic trading. In just a matter of years, Python has emerged as one of the most powerful, versatile and widely used tool for systematic traders.

When I started my journey into Python land, I was struck by two key insights. These two realizations and what they imply prompted me to write a new book, which not only is a whole new type of book for me, but also by far the largest book I have authored.

First, I was incredibly impressed by the power of this language. I have been programming computers since I was ten years old, and it feels very odd to be impressed by a programming language. After all, a programming language is just a tool, and you rarely get impressed by a new hammer.

But Python really is amazing. Compared to other environments, it’s very easy to learn Python and you can get financial analytical tasks done very quickly. Tasks which would take hundreds of lines of code in C# and similar can be done in a single line.

I really do believe that anyone can learn Python and that it is an extremely useful skill for anyone working with backtesting and implementation of trading ideas.

But my second realization was that documentation about Python was very poor. Almost all documentation, books and articles assume that you already know pretty much everything. I didn’t find the online forums particularly helpful either, with most replies simply pointing out that the poster should do his homework before asking silly questions.

The problem I saw with Python is that there was a clear lack of understandable documentation. I found some great books on Python, but they tend to assume that you’re already a programmer, or a data scientist. That’s fine for people like me, who already have a background in such things, but it doesn’t help newcomers to the field.

I wrote this book for two reasons. First, to fill this gap. To open up the field of Python backtesting to all the traders out there using inferior tools. I want to broaden the appeal of Python and get everyone from advanced algo traders to happy hobby traders in on the game.

Trading Evolved does not assume any previous programming knowledge. At all. It does assume that you are sufficiently interested in trading that you are willing to put in a bit of time and effort.

This book is unlike any of my previous books. This book aims to take you from zero to a level of knowledge about Python backtesting that can make you dangerous out there. But this is not just a programming book. This is a trading book.

My previous books explained one trading strategy per book. This book explains many trading strategies. While my previous books tried to explain all the rules in enough detail that you could try to replicate it at home, Trading Evolved actually shows you all of the source code.

I hope you’ll like the book, and I very much appreciate if you would do an Amazon review.

Kindle or Paperback

Trading Evolved will be available in both Kindle and Paperback. So which one should you pick?

This is a big book, at nearly 500 pages and it’s packed with information. I suspect that most people will want to be able to quickly flip back and forth in the book, looking up syntax and information. They probably want to put sticky notes in there, scribble comments and underline. It’s a book that you will most likely read more than once. Perhaps even read a chapter or two, and then move to a computer to try out your new skills. Those things are clearly easier with a paperback.

I read a lot of books, mostly on my Kindle device. This kind of book though, I would personally prefer to have as a paperback on my desk.

For this reason, I have differentiated the pricing significantly. The paperback will have a premium price tag. This is a unique book, with content not found in any other book, and it is a substantial book with nearly 500 pages packed with practical, in-depth content, which took me a year to write. But I will price the Kindle version at just $9.99, to reflect the fact that I personally see the hardcover as more useful. I will also allow those who bought the paperback version to buy the Kindle in addition for just $2.99, so that you can have both versions.

I hope you will find this a fair proposition.

Updates and Errata

As expected, some updates are necessary. In a book like this, it’s impossible to get everything perfect for all kinds of environments and to predict ever updating third party software.

You will find an updating article of issues and solutions here.


There are two separate downloads for this book. The source code file contains all code samples used in the book, while the data file contains random data generated for testing, as discussed in the book.

Table of Contents

1      About this Book                                                                          1

The Trading Strategies in this Book                                                                                                                       2

How to Read this Book                                                                                                                                               3

How this book is written                                                                                                                                            4

How the code is written                                                                                                                                             5

Errata                                                                                                                                                                                 5

Support                                                                                                                                                                             6

2      Systematic Trading                                                                   7

Trading Approach Validation                                                                                                                                   7

Scientific Approach                                                                                                                                                      8

Consistent Methodology                                                                                                                                        10

Time Management                                                                                                                                                     11

3      Developing Trading Models                                                13

Model Purpose                                                                                                                                                            13

Rules and Variations                                                                                                                                                 15

Handling Data                                                                                                                                                             17

Asset Class                                                                                                                                                                    18

Investment Universe                                                                                                                                                19

Allocation and Risk Level                                                                                                                                        20

Entry and Exit Rules                                                                                                                                                  20

Rebalancing                                                                                                                                                                  21

4      Financial Risk                                                                            23

Quantifying Risk                                                                                                                                                         23

Mark to Market                                                                                                                                                            25

Common Risk Fallacies                                                                                                                                            26

Risk as Currency to Buy Performance                                                                                                                 30

5      Introduction to Python                                                       34

Some Assembly Required                                                                                                                                        34

Python Emerges as the Logical Choice                                                                                                              36

Programming Teaching Approach                                                                                                                       37

Installing Python on your Computer                                                                                                                 38

Let’s Run Some Code                                                                                                                                                39

Working with Jupyter Notebook                                                                                                                          46

Dictionary Lookup                                                                                                                                                     47

Conditional Logic                                                                                                                                                       50

Common Mistakes                                                                                                                                                     51

Installing Libraries                                                                                                                                                     54

6      Bring out the Pandas                                                             57

Documentation and Help                                                                                                                                       61

Simple Python Simulation                                                                                                                                      65

Making a Correlation Graph                                                                                                                                  71

Prettier Graphs                                                                                                                                                            76

7      Backtesting Trading Strategies                                        84

Python Backtesting Engines                                                                                                                                   86

Zipline and Quantopian                                                                                                                                          88

Pros and Cons                                                                                                                                                              90

Installing Zipline                                                                                                                                                        91

Problems with Installing Zipline                                                                                                                          95

Zipline and Data                                                                                                                                                         95

Ingesting the Quandl Bundle                                                                                                                                 97

Installing Useful Libraries                                                                                                                                       99

Where to Write Backtest Algos                                                                                                                            100

Your First Zipline Backtest                                                                                                                                   101

Portfolio Backtest                                                                                                                                                    108

Data Used for this Book                                                                                                                                         115

8      Analyzing Backtest Results                                               116

Installing PyFolio                                                                                                                                                    116

Portfolio Algorithm to Analyze                                                                                                                           117

Analyzing Performance with PyFolio                                                                                                               122

Custom Analysis                                                                                                                                                       129

Day Snapshot                                                                                                                                                            131

Custom Time Series Analytics                                                                                                                             135

9      Exchange Traded Funds                                                      142

The Good                                                                                                                                                                    142

The Bad                                                                                                                                                                        143

The Worst                                                                                                                                                                    149

Shorting Exchange Traded Funds                                                                                                                      155

10   Constructing ETF Models                                                   158

Asset Allocation Model                                                                                                                                          160

11   Equities                                                                                      167

The Most Difficult Asset Class                                                                                                                             167

A word on Methodology                                                                                                                                        169

Equity Investment Universe                                                                                                                                169

Dividends                                                                                                                                                                    171

12   Systematic Momentum                                                         174

Replicating this Model                                                                                                                                           174

Momentum Model Rules Summary                                                                                                                  175

Investment Universe                                                                                                                                              176

Momentum Ranking                                                                                                                                               177

Position Allocation                                                                                                                                                  185

Momentum Model Logic                                                                                                                                       187

Downside Protection                                                                                                                                              190

Momentum Model Source Code                                                                                                                        192

Performance                                                                                                                                                               204

Equity Momentum Model Results                                                                                                                    205

13   Futures Models                                                                      211

Futures Basics                                                                                                                                                           212

Futures Mechanics and Terminology                                                                                                               214

Futures and Currency Exposure                                                                                                                         218

Futures and Leverage                                                                                                                                             219

14   Futures Modeling and Backtesting                               221

Continuations                                                                                                                                                           226

Zipline Continuation Behavior                                                                                                                           229

Contracts, Continuations and Rolling                                                                                                             230

15   Futures Trend Following                                                   233

Principles of Trend Following                                                                                                                             234

Revisiting the Core Trend Model                                                                                                                       236

Model Purpose                                                                                                                                                          237

Investment Universe                                                                                                                                              238

Trading Frequency                                                                                                                                                  239

Position Allocation                                                                                                                                                  239

Entry Rules                                                                                                                                                                 244

Exit Rules                                                                                                                                                                     245

Costs and Slippage                                                                                                                                                  246

Interest on Liquidity                                                                                                                                               247

Trend Model Source Code                                                                                                                                    248

Core Trend Model Results                                                                                                                                    260

16   Time Return Trend Model                                                   266

Investment Universe                                                                                                                                              267

Trading Frequency                                                                                                                                                  267

Position Allocation                                                                                                                                                  268

Trading Rules                                                                                                                                                             268

Dynamic Performance Chart                                                                                                                               269

Time Return Source Code                                                                                                                                     270

Time Return Model Performance                                                                                                                       275

Rebalancing                                                                                                                                                                281

17   Counter Trend Trading                                                       283

Counter Model Logic                                                                                                                                              285

Quantifying Pullbacks                                                                                                                                            287

Rules Summary                                                                                                                                                         288

Counter Trend Source Code                                                                                                                                289

Counter Trend Results                                                                                                                                           293

18   Trading the Curve                                                                 298

Term Structure Basics                                                                                                                                             298

Quantifying Term Structure Effect                                                                                                                     302

Curve Model Logic                                                                                                                                                   304

Curve Trading Source Code                                                                                                                                 306

Curve Trading Results                                                                                                                                            314

Model Considerations                                                                                                                                           317

19   Comparing and Combining Models                                  319

Combining the Models                                                                                                                                          322

Implementing a Portfolio of Models                                                                                                                325

20   Performance Visualization and Combinations          327

Storing Model Results                                                                                                                                            327

How the Model Performance Analysis was done                                                                                         328

How the Combined Portfolio Analysis was done                                                                                        332

21   You can’t beat all of the Monkeys all of the Time   336

Mr. Bubbles goes to Wall Street                                                                                                                          338

The Problem is with the Index                                                                                                                            346

Finding Mr. Bubbles                                                                                                                                                349

22   Guest Chapter: Measuring Relative Performance     353

23   Importing your Data                                                             370

Making a Bundle                                                                                                                                                       371

Zipline and Futures Data                                                                                                                                      381

Futures Data Bundle                                                                                                                                               383

Patching the Framework                                                                                                                                       392

24   Data and Databases                                                               394

Your Very Own Securities Database                                                                                                                  397

Installing MySQL Server                                                                                                                                        398

Making an Equities Time-Series Table                                                                                                            400

Populating the Database                                                                                                                                      402

Querying the Database                                                                                                                                          408

Making a Database Bundle                                                                                                                                   411

25   Final Words – Path Forward                                               415

Build Your Own Models                                                                                                                                         415

Other Backtesting Engines                                                                                                                                   416

How to Make Money in the Markets                                                                                                                 418

References                                                                                      419

Index  420




  1. Holding Pattern

    Is there a way to pre-order the hardcover book ?

  2. I’m at 50% with the book love it so far, I’m here for the backtesting time 🙂

    I highly recommend the book for anyone looking to get started with trading seriously and creating your own strategies.

    The book is a shortcut i wish was available 1+ year ago when I had to jump between books just to make sense on a secretive it seemed at the time industry.

    Thanks Andreas for writing it

    • Thanks, Mark! Much appreciated. And it’s exactly the kind of comment that I’m hoping for.

      My starting point, with all my books, has been that I want to write books for a younger version of myself. Books which I wish had been available to me earlier on. When I publisher asks me who the target audience is, my response is always “me, X years ago”.

      It would be great if you could write an Amazon review.

  3. Exactly the book I was thirsting for!
    Picked up the print as well as Kindle version. Am at page 99 – super stoked!
    Many thanks!

  4. Andreas,

    Hello. I picked up the hardcover book and enjoying it thus far. Even though you wrote it such that an inexperienced person could learn Python, I still find it challenging. Perhaps it’s just me.

    That said, there are many typos throughout. The second edition will need some editing.


  5. Andreas,

    Hello. You mentioned in “Trading Evolved” that you have tested the Python coding in your book across various platforms (Windows, Linux and Mac OS). If so, I want to offer a suggestion to recreate these environments so that Python and its associated libraries can be replicated in other users personal computers.

    Pages 66-67 of the Conda documentation [ here ==> ] describe how to export a file that contains all the packages and versions of an environment where Python, and most importantly Zipline, have been successfully tested and used.

    If you have created those environments across the three platforms, exporting the “environment.yml” file for each platform, and sharing it on this website would go a long way to resolving installation and implementation problems. Users can download the file for their platform and then install it on their personal computer to recreate the tested environment.

    I am an accountant and not a coder. So I may be over simplifying what is involved. Nevertheless, this sounds like a convenient way to get your readers up and running very quickly.

    Thanks for your consideration.


  6. Hi Andreas,

    I have tried getting zipline running a couple of years ago and failed, picked up your book and with your patches it finally works. Thank you so much!

    Right no I’m struggling with getting my own bundles with futures “minute” data to work, I have managed to patch zipline and ingest it but I have problems loading it into my algorithms. I was wondering if you have managed to do this as it is not described in your book and if so do you mind share your knowledge.

    And again thanks for a great book!

    • Hi Hakan,

      I haven’t worked with minute futures data for Zipline, but I know that minute level data can be a little trickier.

      If I try it out and solve it, I’ll report back.

      I had a few requests to set up a forum here for readers to discuss Zipline stuff. It would be fun to get a community going to discuss, I’m just worried that it will turn into a place where everyone asks questions, and no one replies…

      Also, I’d be grateful if you could write an Amazon review for the book, Hakan!


  7. I got zipline up and running and I have also reached the bundles and ingest. Set QUANDL_API_KEY works (at least no error messages). I changed the file as per page 96. When I run “zipline ingest -b quandl” (page 99) I get an error message. Look like it’s “first_date = datetime(1930,1,1)” that cause problems. I can’t find anything about ingest on the internet that could help me. It can be difficult to find out whether it’s a software or user issue. I don’t want to write loads of support questions that no one answer. Instead I just ask if anyone else also got stuck here and perhaps how the problem was solved.

    • Hey Henk,

      Post your error message and I’ll take a look. Perhaps me or someone else has seen it before.

      In my view, getting past the Zipline installation part is the main hurdle. The Quandl stuff you won’t really need, and I mostly included it to get some sort of data up early in the book.

      For any sort of even semi serious stuff, you’ll need to hook up your own data. If it’s just Quandl holding you up, I’d advise to simply skip it. You can’t do all that much with Quandl anyhow.

      More important is to set up your own bundle and connect to your own data. That’s explained in the back, chapters 23 and 24.


  8. Hello Andreas,

    Thanks for writing this excellent book. I had early awaited for this book once you announced about it on twitter and probably the first one to purchase it on Amazon. The information you have shared is not easily available to retail traders and you have shared enough information to enable retail traders to compete with professionals.

    I have already written my review on Amazon and have recommended this book on couple of popular trading forums. Thanks again and hope to see more such books from you.

    PS: Please have the book edited in next version as there are many typos and errors, nothing major but it will help improve the readability.


  9. @Andreas, It looks like Amazon reviews from regional websites are not showing up in their global website, my review is not shown at ..:-)

  10. Hi Andreas,

    Just getting started with the book. Seems very promising. I was just going to start with the example on page 58, but can’t find the SPX data on the Dropbox link. AM I missing something? I’ve tried doing the exercise by taking the file from the stocks folder (editing to have just date and close), but I’m getting weird charts -it’s like both price and SMA jump around vertically a lot over very very short time-frames so it’s like someone has scribbled over the chart, just following the trend. I’m assuming there’s something I’m missing with those data as it relates with this exercise.

    Thank you very much


    • Hi David,

      The file you’re looking for is in the folder for that chapter. Under Chapter 6 folder, there’s a file called sp500.csv which contains historical data for that index.


  11. hello
    i bought this book from Amazon and tried to execute the example code of chapter7 “First Zipline Backtest.ipynb”

    i got these error responses:
    ValueError Traceback (most recent call last)
    in ()
    4 # Import Zipline functions that we need
    —-> 5 from zipline import run_algorithm
    6 from zipline.api import order_target_percent, symbol

    ~\Anaconda3\envs\env_zipline\lib\site-packages\zipline\ in ()
    23 from . import data
    —> 24 from . import finance
    25 from . import gens
    26 from . import utils

    ~\Anaconda3\envs\env_zipline\lib\site-packages\zipline\finance\ in ()
    14 # limitations under the License.
    —> 16 from . import execution, trading
    18 __all__ = [

    ~\Anaconda3\envs\env_zipline\lib\site-packages\zipline\finance\ in ()
    21 from trading_calendars import get_calendar
    —> 23 from zipline.assets import AssetDBWriter, AssetFinder
    24 from zipline.assets.continuous_futures import CHAIN_PREDICATES
    25 from import load_market_data

    ~\Anaconda3\envs\env_zipline\lib\site-packages\zipline\assets\ in ()
    14 # limitations under the License.
    —> 16 from ._assets import (
    17 Asset,
    18 Equity,

    __init__.pxd in init zipline.assets._assets()

    ValueError: numpy.ufunc has the wrong size, try recompiling. Expected 192, got 216

    could you help me to solve these errors ?
    Thank you very much

    sorry,English is not my native language
    Hope you can understand what i mean

  12. Hi guys,

    I am unable to buy kindle copy of the book. Seems like it’s unable currently for purchase.
    I just want to confirm that is it just me who is getting this message or it’s really unable. I am curious whether amazon is blocking purchase from some countries . I have read free 6 chapters from the sample available on amazon and really like the book.

    • Hi Wajahat,

      The book is available on Kindle, and I can see quite a few Kindle copies sold today.

      At times Amazon have some odd regional rules. Based on your IP, I’m guessing that you’re in Pakistan, and perhaps doesn’t sell Kindle there. I had a similar issue with Australia.

      Sorry, this is all Amazon policy stuff, and I have no control at all over it. I suggest to contact Amazon customer support and asking.


  13. Hej Andreas,

    I got some of the errors like the “JSON decoding” stuff as well. The solution was to correct indentation errors in some files. That was perhaps the punishment for expecting code to run after I just copied and pasted it into my JP Notebook 😉

    (Win 10 Pro, Anaconda 1.9.7, Python 3.5, zipline 1.3.0)

    If somebody still has an issue with the ingestion of the data, you could try the following:
    – Start an environment from Anaconda with “Open Terminal” (environment is activated then)
    – At the prompt type: zipline bundles (that shows all available bundles on your machine)
    – Either it shows the bundles or you’ll see the error traceback which makes it easy to correct the certain files

    This worked for me as it showed some wrong indentations in the “” and “” files. The backtest run after correcting the typos.

    And not to forget: Thanks for the book, Andreas!

    Best regards

  14. Hi,
    thanks for the great book! I hope to have an Amazon review out soon.
    I wanted to seek some clarification on “ZIPLINE cannot handle other currencies”, i.e. only 1 main base currency which is rather disappointing for a global futures portfolio. Is there a workaround available?
    Having EUR.USD daily data and creating a look-up table to do on the spot currency conversion on Entry/Exit seems simple enough, what is the big issue with ZIPLINE and FX/Currencies?

    • Thanks, Matthias!

      The single world currency is a clear issue with Zipline. It’s of course a bigger issue for equities than futures.

      The good news is that Zipline is open source, and anyone can fork it. If you’d like to take a shot at fixing it…

      I didn’t dig into this part of the framework, but my understanding is that this is quite a deep issue and not easy to mend.

      A possible workaround for international equities would be to pre-adjust your time series before ingesting the bundle. That is, relcalculate all series to a common base currency first, then test your strategies on that.

  15. Hi Andreas,
    another great book. Thanks so much, also for the two others before!
    At the end of the book when briefly discussing other backteting engines you are mentioning options trading. Are there any backtesting solutions you would recommend to retail options traders?

    • Hi Markus,

      My sincere advise to retail traders is to stay clear of options. In particular if the reason for using options it to gain leverage. Options is a pro game where hobby guys are at a severe disadvantage.

      Timeo Danaos et dona ferentes.

      Having said that, I am not aware of any decent retail backtester that properly supports options.

  16. After reading Stocks on the Move, I implemented my own modified version in a custom backtest engine in python. I researched the backtest engines available at the time, zipline included, and found out all of them were too complicated.

    Now with your book I finally was able to do a much more professional and robust backtest than with my home made engine, with zipline. Thanks Andreas!

  17. Hi Andreas/anyone

    I bought Trading Evolved from Amazon (Kindle format). I must say this is an AMAZING book. Thank you Andreas for sharing your invaluable knowledge. Your hard work and your effort are greatly appreciated. Finally I have a chance to set up my own testing environment with open source programming language.

    I have been following the book step by step. I managed to install everything including zipline. I have patched the framework ( and and it seems that it can ingest quandl ok. So I am up to “Your First Zipline Backtest” now.

    Here I am stuck. I try to run the code but it gives me errors so I am unable to reproduce the charts. I don’t know how to fix it. I have no experience in Python programming in the past.

    Is there a forum I can ask questions? It seems that people are asking technical questions on the Errata and Updates page but I am unable to post comment for unknown reasons…

    Can Andreas/anyone please point me to where I can ask technical questions from the book and get answers?

    Thank you so much for your help.

    • Hi Henry,

      Thank you for your kinds words, and thanks for pointing out the comments issue!

      I just figured out why you couldn’t comment. As comment spam has been increasing lately, I had set the site to automatically close comments on articles older than two weeks. That’s usually enough, but clearly not for a constantly updating article like the errata page. Should be fixed now.

      I had meant to set up a forum of some sort, but didn’t find the time. On advise, I looked into using GitHub for this as well, but I found the GitHub community quite hostile to that idea. Pretty much the same kind of replies that you tend to get on StackOverflow: “Instead of helping you with your issue, I’m going to tell you how stupid you are for trying this in the first place.” Odd why all these people sign up to such sites just to post replies of that sort. Reminds me of the standard reply that UNIX guys had to every question back in the 90s. “RTFM”.

      For now, here are some places where people have posted lots of questions and answers:

      There’s some great advise in the Quantopian thread, that I haven’t yet copied over to this site.

      I’m following these discussions as well and will jump in to try to help out.

      Also, and I know I say this all the time: Please write an Amazon review for the book. These days, that’s the most important thing for a book, and as opposed to so many others, I refuse to pay for fake reviews or have ‘giveaways’ to people who review. It only matters when it’s a real person and real review.

      • Thank you Andreas. I will post my technical question on those two threads.

        I tried to leave a positive review on Amazon for your book. HAHA unfortunately I did not meet the minimum eligibility requirement: you need to spend at least $50 on Amazon in the last 12 months to be able to leave a review. I spent below that so very sorry I am unable to help you on that…

        If I get to a stage that I am eligible for doing reviews. I will definitely do one for your book.

      • Ah, that explains. I didn’t know that they started with that rule, but it makes sense. The amount of fake reviews on Amazon was really spiraling out of control, and hopefully these new rules are helping.

        A few years ago I saw a new book launched in the same space as my books, by an author I’ve met a few times. If you’ve had books on Amazon, you learn to interpret the Amazon Ranking numbers, and I could see on his that he probably sold about 300-400 books the first week. And he had 300 reviews in the same time…

        This particular author is a nice guy, so I won’t call him out, but it was painfully clear that he bought a few hundred fake reviews.

        My experience is that around half a percent of people who buy the book will post a review. Slightly higher if you keep bugging people about it. 🙂

  18. Hi, Andreas. I purchased your kindle book. It is a great one. Really like it. I have a question on charter 12. For calculating annual slope, your code is ann_slope = (np.power(np.exp(slope), 252) -1)*100. Should it be ann_slope = (np.power(1+np.exp(slope)), 252) -1)*100?
    I will appreciate your response.

  19. Hi,

    I bought the book and I’m now trying to run your futures trading systems on my platform. I installed zipline and python 35 correctly, at least your equity model works. However when I’m trying to your your Jupyter Notebook files for the futures system I get an error message about the “bundle”.

    In your Trend model I get the message: “UnknownBundle: No bundle registered with the name ‘rand_fut'” and as well there is a message “widget Javascript not detected”.

    Can anyone help?

Leave a Reply to Joerg Cancel reply

Your email address will not be published. Required fields are marked *