Don't Miss
Home » Articles » Trading Evolved – Errata and Updates

Trading Evolved – Errata and Updates

A book like Trading Evolved will without a doubt have errors. On top of errors, updates may also be needed as new versions of dependent software packages are released. I will keep a running log on this site of issues found, and suggested solutions. After this list grows long enough, I will update the book itself, and put a version number on it.

This article will be continuously updated.

 

Book Version 1.0

Version 1.0 of the book was released on August 8, 2019.

Unable to Install Zipline with Conda version 4.7.10

Conda version 4.7 seems to break some dependencies and may result in an inability to install Zipline using the syntax “conda install zipline -c quantopian”.

Workaround 1 – Downgrade Conda

https://github.com/quantopian/zipline/issues/2514

Workaround 2 – Install using pip

https://www.zipline.io/install.html#installing-with-pip

 

Typo in “Patching the Framework”

On page 96 there’s a typo and the wrong file name is stated. This was the very last thing I did on the book before shipping it, as the issue that needed patching appeared at the last moment.

The file to be changed is “benchmarks.py”, not “loader.py”.

Here is the complete, corrected version.

Zipline, like most software in Python world is not only free, but open source. You can see and edit all the code as you like, and one big advantage of this is that we can make changes and even fix bugs when needed. You may wonder why you would ever want to go and edit someone else’s code, but it can be very useful to have this possibility.

While writing this book, an interesting example of such a situation came up. One day, all the backtests suddenly stopped working, with an error message about failing to load benchmark data from some web address. As it turns out, there is a web call executed during backtests, where Zipline tries to pull data from an online source. This source, much like what happened to many other free data sources, suddenly stopped working without warning.

As of writing, this issue has not yet been addressed. But no worries, we can do it ourselves easily. We don’t actually need this benchmark data for anything that we will do in this book, and the easiest fix is to simply remove the web call and just return empty data.

My version of Zipline is 1.3, and if you’re working with the same version, you likely need to do this fix manually. It won’t take long.

First locate a file called benchmarks.py, which should be in your Zipline installation folder. You can use the file system search tools to locate it. If you are on Windows, the path will probably be similar to this.

C:\ProgramData\Anaconda3\envs\zip35\Lib\site-packages\zipline\data

It’s always a good idea to keep a backup of the original code, so rename this file to keep a copy. Then make a new file, with the name benchmarks.py, and put the following code in it before saving.

This code will simply return a data series from 1930 to 2030 with all zero values, which will effectively sidestep this web call issue, with no negative impact.

Addition to Patch

You may also need to bypass the cache in loader.py, in the same folder:

https://github.com/quantopian/zipline/issues/2480#issuecomment-504387554

 

Zipline Installation: failed with current_repodata.json

Error:

Collecting package metadata (current_repodata.json): done
Solving environment: failed with current_repodata.json, will retry with next repodata source.

Solution:

1) Update Conda to the latest version:

2) Install the free channel:

3) install Zipline:

 

Trouble Ingesting Quandl

Error:

“ValueError: Boolean array expected for the condition, not float64”

Solution:

Downgrading Pandas to 0.18.1

 

Jupyter version 5.0.0 not starting

Solution:

Downgrading “tornado” from 5.1.1 to 4.5.3

 

Trouble ingesting Quandl on Mac

Try

 

Typo Chapter 23 – Bundle Name

In chapter 23, you’re advised to ingest the random stocks bundle using

But that’s not the name of the bundle that we just created a few lines above. The name in used in the bundle was random_stock_data, so we need to use that name when ingesting.

Similar typo in regards to the futures bundle. The name of the file in the sample code is random_futures_data:

And

Note that you can call your bundles whatever you like, but the file names need to match the references, and the registered bundle name needs to match the ingest call.

105 comments

  1. Steven Petersen

    Good new book so far. The following are no big deal but though I’d mention them.

    “If the volatility is exactly half in Microsoft, you would theoretically achieve the same risk level if you invest twice as much in Tesla.” should be “…twice as much AS in Tesla” ?

    “You can create both a folder and a new Python file through that dropdown on the right side, which you can see in Figure 5‑2.” should be “…a new Python FOLDER” ? There is an option to create a file so I got confused.

    • Yes, that first one is unfortunate. Leaving out ‘as’ gave the sentence the opposite meaning…

      But the second sentence seems fine to me, unless I’m still missing something. It’s not a Python folder, it’s a regular folder that you can create. Or ‘directory’ if you’re so inclined.

      So you can create folders in Jupyter, as well as Jupyter Notebook python files. Click the dropdown, and you’ll see.

  2. hi Andreas, thank you for the book. Great book. Hope to be even better at backtesting in time to come. By the way, the sp500 downloaded did not show sp500 values but it showed all the components within instead. My understanding from the book is 2 columns, 1 date and the other would be values under sp500. Am i right to say that? Thank you for taking the time to read this.

  3. Zipline Installation: failed with current_repodata.json

    Missing a dash led to another error. For step 2 it should be:

    conda config –set restore_free_channel true

    I’m loving the book so far. I’m no coder, but have found my interest in investing a useful tool to motivate me to solve problems and tinker.

  4. https://github.com/ContinuumIO/anaconda-issues/issues/1423

    I had an issue trying to install the nb_conda package (pg.101) and while I didn’t save the error message it was something to do with nb_conda not being compatible with Python 3.5. Anyway I used the following command in the terminal from the link above to get it to install
    conda install -c conda-forge nb_conda

  5. Jupyter notebook not downloaded in my zip35 environment, open in jupyter greyed out, and cannot download notebook==6.0

    also can’t ingest quandl already downgraded pandas, or at least i think i did, just used

    conda install pandas=0.18.1

  6. which version of conda I should use to install zipline.

    First part of the message says
    “Workaround 1 – Downgrade Conda” , conda install conda=4.6.11

    The last part of the message says
    1) Update Conda to the latest version:

    What should I do?

  7. Just acquired “Trading Evolved” and want to thank you for your efforts in writing the book. I am finding it extremely useful in my quest to become proficient in using Python for financial analysis and equities trading.

    In the course of following along with the book in Jupyter Notebook I encountered an error in running “first Zipline backtest” as follows:

    ValueError: SQLite file ‘C:\\Users\\r1100/.zipline\\data\\quandl\\2019-08-21T20;57;11.306361\\assets-6.sqlite’ doesn’t exist

    So my question is what is this file and what is required to bring it into existence? Thank you.

    • That sounds like an error during bundle ingest. If you interrupt the ingest process, or if it for any reason fails, this error shows up. Try ingesting it again.

      Also, the Quandl bundle is very limited and I would very much recommend making your own bundle, for your own data, as explained in the later chapters in the book.

    • I don’t recall doing anything that would cause the ingest process to be interrupted. I will certainly try the ingest process again but with the verbose mode on (note I mostly use iPython) to get a better idea of what is going on should the error repeat. I think I will start making my own bundles – I prefer having more control over the overall process.

    • Oh, and be sure to start the kernel in the notebook after ingesting. In case you had the notebook running while doing the ingest, you’ll need to restart the kernel.

  8. Stephen Hankinson

    Great book Andreas. I’ve enjoyed all of your books to date.

    I noticed an issue with the dividend code when trying to import data with dividends. The divs.append method inside the process_stocks function is creating a local copy of the divs DataFrame which doesn’t apply the changes to the divs DataFrame in the random_stock_data function. You can confirm this by adding a print(divs) right before the adjustment_writer.write call, if using a dataset with dividends, and you’ll see the DataFrame being written is empty.

    A simple fix is to change the dividend check to the following:


    # If there's dividend data, add that to the dividend DataFrame
    if 'dividend' in df.columns:

    # Get the current highest index
    idx = len(divs)

    # Append this stock's dividends to the list of all dividends
    tmp = df[df['dividend'] != 0.0]['dividend']
    for ex_date, amount in tmp.iteritems():
    divs.loc[idx] = [sid, amount, ex_date, pd.NaT, pd.NaT, pd.NaT]
    idx = idx + 1

    Another thing I noticed when importing data from alphavantage is that the if your data is ordered newest to oldest you’ll get an error when importing it. This can be fixed by adding df.sort_index(inplace=True) right after the pd.read_csv call.

  9. https://github.com/quantopian/zipline/issues/1591

    im trapped here, please help, already changed the zipline-scrypt.py file, did not work, getting this

    Traceback (most recent call last):
    File “C:\Users\JAY\Anaconda3\envs\zip35\Scripts\zipline-script.py”, line 11, in
    load_entry_point(‘zipline==1.3.0’, ‘console_scripts’, ‘zipline’)()
    File “C:\Users\JAY\Anaconda3\envs\zip35\lib\site-packages\pkg_resources\__init__.py”, line 484, in load_entry_point
    return get_distribution(dist).load_entry_point(group, name)
    File “C:\Users\JAY\Anaconda3\envs\zip35\lib\site-packages\pkg_resources\__init__.py”, line 2707, in load_entry_point
    return ep.load()
    File “C:\Users\JAY\Anaconda3\envs\zip35\lib\site-packages\pkg_resources\__init__.py”, line 2325, in load
    return self.resolve()
    File “C:\Users\JAY\Anaconda3\envs\zip35\lib\site-packages\pkg_resources\__init__.py”, line 2331, in resolve
    module = __import__(self.module_name, fromlist=[‘__name__’], level=0)
    File “C:\Users\JAY\Anaconda3\envs\zip35\lib\site-packages\zipline\__init__.py”, line 23, in
    from . import data
    File “C:\Users\JAY\Anaconda3\envs\zip35\lib\site-packages\zipline\data\__init__.py”, line 1, in
    from . import loader
    File “C:\Users\JAY\Anaconda3\envs\zip35\lib\site-packages\zipline\data\loader.py”, line 22, in
    from .benchmarks import get_benchmark_returns
    File “C:\Users\JAY\Anaconda3\envs\zip35\lib\site-packages\zipline\data\benchmarks.py”, line 23
    data = data[‘close’] return data.sort_index().iloc[1:]
    ^
    SyntaxError: invalid syntax.

    I’ve been stuck with setting up the environment for quite a while now

    • Hello Jay,

      It looks like a syntax error on line number 23 of the file benchmarks.py:

      File “C:\Users\JAY\Anaconda3\envs\zip35\lib\site-packages\zipline\data\benchmarks.py”, line 23
      data = data[‘close’] return data.sort_index().iloc[1:]
      ^
      SyntaxError: invalid syntax.

      I think you have the return statement in the same line as data = data[‘close’]

      Please change the content of this file “benchmark.py” exactly as follows:

      import pandas as pd
      from datetime import datetime
      from trading_calendars import get_calendar

      def get_benchmark_returns(symbol):
      cal = get_calendar(‘NYSE’)
      first_date = datetime(1930,1,1).date()
      last_date = datetime(2030,1,1).date()
      dates = cal.sessions_in_range(first_date,last_date)
      data = pd.DataFrame(0.0,index=dates,columns=[‘close’])
      data = data[‘close’]
      return data.sort_index().iloc[1:]

      • I put down the book for two months after not being able to crack this, now it got fixed on its own, but now the kernel in my jupyter died(for reasons i cant understand), had to delete the whole environment and now I’m stuck here again, frustrating, I’ve tried everything in this forum no solution, I’m stuck

  10. Hi Andreas,

    Thank you very much for writing this book.

    When attempting to run the code in “Your First Zipline Backtest”, I get an error when trying to run the moving average window that says “NameError: name ‘context’ is not defined”.

    I’m sure this is something basic that I am missing, though it stops the whole thing from working. Would you happen to know what I am missing in this case.

    Thanks,
    James

  11. Working on a mac.

    After ingesting the quandl bundle, I ran the first zipline backtest and got the following error:

    ValueError: No JSON object could be decoded

  12. Hey Andreas, great book so far.

    In regard to the ‘Making a correlation Graph’, my correlation graph came out a bit different compared to the one showed on the book. (more spikes)

    I used the set of data you provided which is ‘indexes’ in chapter 6 pandas folder.

    Don’t know if it’s the matplotlib format/version or its the way the dataset in computed. Should we expect similar differences throughout the book?

    Thank you.

  13. Hi Andreas, great book and i am digging my way through it. Right stuff at the right time so to speak. Got environment set up on desktop – check! However, laptop is posing and issue re Quandl – despite all same as desktop, i am getting the dreaded “failed to create process”. i tried your suggested remedy of apply a double does of “” to the relevant file but alas…still same result ie “failed t0 create process”. Do you have other good ideas of where to look/what to do? Thanks in advance.

    Michael

    • Hi Michael,

      This is most likely an issue regarding installation path and probably there are spaces in your path. There’s a thread somewhere in the Zipline GitHub about this, and the solution likely involves modding the path with double quotes. I understand you tried this, but it’s probably something highly related.

      Sorry I can’t be more specific, but it’s difficult without actually seeing your exact setup. I’m pretty sure you’re on the right track though. This is a classic error relating to Windows and spaces in the path to the interpreter.

  14. Hello Andreas thanks for the book,

    On page 96 what do you mean “You may also need to bypass the cache in loader.py”?
    Do you mean override the whole file or just the section of the code between the triple quotes?

    Thanks

  15. Hey Andreas,

    You are commendable for writing this book, it is well written, clear, and exactly what young python developers are looking for!

    Was wondering if you, or anyone else watching this thread would be able to assist here. I am having the same issue as mentioned on this github post (https://github.com/quantopian/zipline/issues/2532), and as insult to injury I am unable to downgrade Anaconda to 4.6.11. It looks like this issue has arisen fairly recently based on what the community is saying.

    Has anyone else had this issue?

  16. I can not get past this error, JSONDecodeError: Expecting value: line 1 column 1 (char 0). I’ve read all the github threads, and have tried changing the benchmarks.py and loaders.py files, but to no avail.

    Any suggestions, on mac BTW.

    Thanks

    • Same problem here and I’m using Windows. This happened while trying the first zipline backtest:

      JSONDecodeError Traceback (most recent call last)
      in ()
      53 capital_base = 10000,
      54 data_frequency = ‘daily’,
      —> 55 bundle = ‘quandl’)

    • HELP!!!

      —————————————————————————
      JSONDecodeError Traceback (most recent call last)
      in
      53 capital_base = 10000,
      54 data_frequency = ‘daily’,
      —> 55 bundle = ‘quandl’)

      ~\Anaconda3\envs\zpline35\lib\site-packages\zipline\utils\run_algo.py in run_algorithm(start, end, initialize, capital_base, handle_data, before_trading_start, analyze, data_frequency, data, bundle, bundle_timestamp, trading_calendar, metrics_set, default_extension, extensions, strict_extensions, environ, blotter)
      428 local_namespace=False,
      429 environ=environ,
      –> 430 blotter=blotter,
      431 )

      ~\Anaconda3\envs\zpline35\lib\site-packages\zipline\utils\run_algo.py in _run(handle_data, initialize, before_trading_start, analyze, algofile, algotext, defines, data_frequency, capital_base, data, bundle, bundle_timestamp, start, end, output, trading_calendar, print_algo, metrics_set, local_namespace, environ, blotter)
      157 trading_calendar=trading_calendar,
      158 trading_day=trading_calendar.day,
      –> 159 trading_days=trading_calendar.schedule[start:end].index,
      160 )
      161 first_trading_day =\

      ~\Anaconda3\envs\zpline35\lib\site-packages\zipline\finance\trading.py in __init__(self, load, bm_symbol, exchange_tz, trading_calendar, trading_day, trading_days, asset_db_path, future_chain_predicates, environ)
      101 trading_day,
      102 trading_days,
      –> 103 self.bm_symbol,
      104 )
      105

      ~\Anaconda3\envs\zpline35\lib\site-packages\zipline\data\loader.py in load_market_data(trading_day, trading_days, bm_symbol, environ)
      147 # date so that we can compute returns for the first date.
      148 trading_day,
      –> 149 environ,
      150 )
      151 tc = ensure_treasury_data(

      ~\Anaconda3\envs\zpline35\lib\site-packages\zipline\data\loader.py in ensure_benchmark_data(symbol, first_date, last_date, now, trading_day, environ)
      214
      215 try:
      –> 216 data = get_benchmark_returns(symbol)
      217 data.to_csv(get_data_filepath(filename, environ))
      218 except (OSError, IOError, HTTPError):

      ~\Anaconda3\envs\zpline35\lib\site-packages\zipline\data\benchmarks.py in get_benchmark_returns(symbol)
      33 ‘https://api.iextrading.com/1.0/stock/{}/chart/5y’.format(symbol)
      34 )
      —> 35 data = r.json()
      36
      37 df = pd.DataFrame(data)

      ~\Anaconda3\envs\zpline35\lib\site-packages\requests\models.py in json(self, **kwargs)
      895 # used.
      896 pass
      –> 897 return complexjson.loads(self.text, **kwargs)
      898
      899 @property

      ~\Anaconda3\envs\zpline35\lib\json\__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
      317 parse_int is None and parse_float is None and
      318 parse_constant is None and object_pairs_hook is None and not kw):
      –> 319 return _default_decoder.decode(s)
      320 if cls is None:
      321 cls = JSONDecoder

      ~\Anaconda3\envs\zpline35\lib\json\decoder.py in decode(self, s, _w)
      337
      338 “””
      –> 339 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
      340 end = _w(s, end).end()
      341 if end != len(s):

      ~\Anaconda3\envs\zpline35\lib\json\decoder.py in raw_decode(self, s, idx)
      355 obj, end = self.scan_once(s, idx)
      356 except StopIteration as err:
      –> 357 raise JSONDecodeError(“Expecting value”, s, err.value) from None
      358 return obj, end

      JSONDecodeError: Expecting value: line 1 column 1 (char 0)

      • This is the error if u did not applied the patch for zipline Andreas mentioned in the book. Also it is in erratas ib this site.
        Still not sure loader.py needs comment out patch since it seems redundant but I do not know zipline much so I applied.
        Once you apply patch, it should be fine.

    • Hi Stephen.

      I finally managed to get passed that problem by also adding:

      from trading_calendars import get_calendar
      from datetime import datetime

      to the benchmarks.py fix that Andreas provided. So the full code would become:

      import pandas as pd
      import requests
      from trading_calendars import get_calendar
      from datetime import datetime

      def get_benchmark_returns(symbol):
      cal = get_calendar(‘NYSE’)
      first_date = datetime(1930,1,1)
      last_date = datetime(2030,1,1)
      dates = cal.sessions_in_range(first_date, last_date)
      data = pd.DataFrame(0.0, index=dates, columns=[‘close’])
      data = data[‘close’]
      return data.sort_index().iloc[1:]

      Moreover, please note that the loader.py contains the following statement twice, so make sure you find them both and apply the triple quotes to bypass them.
      “””
      if data is not None:
      return data
      “””

      I hope that works for you too.

      • Dear Friends,
        I have a similar problem with First Zipline Backtest:

        —————————————————————————
        JSONDecodeError Traceback (most recent call last)
        in ()
        71 handle_data=handle_data,
        72 capital_base=10000,
        —> 73 data_frequency = ‘daily’, bundle=’quandl’
        74 )

        ~\AppData\Local\Continuum\anaconda3\envs\zip35\lib\site-packages\zipline\utils\run_algo.py in run_algorithm(start, end, initialize, capital_base, handle_data, before_trading_start, analyze, data_frequency, data, bundle, bundle_timestamp, trading_calendar, metrics_set, default_extension, extensions, strict_extensions, environ, blotter)
        428 local_namespace=False,
        429 environ=environ,
        –> 430 blotter=blotter,
        431 )

        ~\AppData\Local\Continuum\anaconda3\envs\zip35\lib\site-packages\zipline\utils\run_algo.py in _run(handle_data, initialize, before_trading_start, analyze, algofile, algotext, defines, data_frequency, capital_base, data, bundle, bundle_timestamp, start, end, output, trading_calendar, print_algo, metrics_set, local_namespace, environ, blotter)
        157 trading_calendar=trading_calendar,
        158 trading_day=trading_calendar.day,
        –> 159 trading_days=trading_calendar.schedule[start:end].index,
        160 )
        161 first_trading_day =\

        ~\AppData\Local\Continuum\anaconda3\envs\zip35\lib\site-packages\zipline\finance\trading.py in __init__(self, load, bm_symbol, exchange_tz, trading_calendar, trading_day, trading_days, asset_db_path, future_chain_predicates, environ)
        101 trading_day,
        102 trading_days,
        –> 103 self.bm_symbol,
        104 )
        105

        ~\AppData\Local\Continuum\anaconda3\envs\zip35\lib\site-packages\zipline\data\loader.py in load_market_data(trading_day, trading_days, bm_symbol, environ)
        147 # date so that we can compute returns for the first date.
        148 trading_day,
        –> 149 environ,
        150 )
        151 tc = ensure_treasury_data(

        ~\AppData\Local\Continuum\anaconda3\envs\zip35\lib\site-packages\zipline\data\loader.py in ensure_benchmark_data(symbol, first_date, last_date, now, trading_day, environ)
        215
        216 try:
        –> 217 data = get_benchmark_returns(symbol)
        218 data.to_csv(get_data_filepath(filename, environ))
        219 except (OSError, IOError, HTTPError):

        ~\AppData\Local\Continuum\anaconda3\envs\zip35\lib\site-packages\zipline\data\benchmarks.py in get_benchmark_returns(symbol)

        ~\AppData\Local\Continuum\anaconda3\envs\zip35\lib\site-packages\requests\models.py in json(self, **kwargs)
        895 # used.
        896 pass
        –> 897 return complexjson.loads(self.text, **kwargs)
        898
        899 @property

        ~\AppData\Local\Continuum\anaconda3\envs\zip35\lib\json\__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
        317 parse_int is None and parse_float is None and
        318 parse_constant is None and object_pairs_hook is None and not kw):
        –> 319 return _default_decoder.decode(s)
        320 if cls is None:
        321 cls = JSONDecoder

        ~\AppData\Local\Continuum\anaconda3\envs\zip35\lib\json\decoder.py in decode(self, s, _w)
        337
        338 “””
        –> 339 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
        340 end = _w(s, end).end()
        341 if end != len(s):

        ~\AppData\Local\Continuum\anaconda3\envs\zip35\lib\json\decoder.py in raw_decode(self, s, idx)
        355 obj, end = self.scan_once(s, idx)
        356 except StopIteration as err:
        –> 357 raise JSONDecodeError(“Expecting value”, s, err.value) from None
        358 return obj, end

        JSONDecodeError: Expecting value: line 1 column 1 (char 0)

        Benchmarks.py:
        import pandas as pd
        from trading_calendars import get_calendar
        from datetime import datetime

        def get_benchmark_returns(symbol):
        cal = get_calendar(‘NYSE’)
        first_date = datetime(1930,1,1)
        last_date = datetime(2030,1,1)
        dates = cal.sessions_in_range(first_date, last_date)
        data = pd.DataFrame(0.0, index=dates, columns=[‘close’])
        data = data[‘close’]
        return data.sort_index().iloc[1:]

        I use Windows 10, I’ve read all the github threads, but without succes. Hints are welcome! Many Thanks”

    • Same problem here with the JSON decode error. No fixes seem to work. I’m just testing the First Zipline Backtest code, got it all good including ingesting quandl on Mac Catalina but continue to get:

      ~/opt/anaconda3/envs/zip35/lib/python3.5/json/decoder.py in raw_decode(self, s, idx)
      355 obj, end = self.scan_once(s, idx)
      356 except StopIteration as err:
      –> 357 raise JSONDecodeError(“Expecting value”, s, err.value) from None
      358 return obj, end

      JSONDecodeError: Expecting value: line 1 column 1 (char 0)

      • After adopting changes in benchmarks.py and loader.py as recommended, I am not getting the error:

        File “”, line 3
        cal=get_calendar(‘NYSE’)
        ^
        SyntaxError: invalid character in identifier

        Which seems impossible.

      • Alas there ARE hidden characters in benchmarks.py. Clean them up and things work fine. Thank you — me — for solving!

        fwiw

  17. Thank you for this community here. I am currently facing a zipline issue. Used to work okay when I followed the instructions in chapter 7. Ingested the customized bundle as mentioned in chapter 23 but it did not work. Was unsure why so I uninstall anaconda and reinstalled everything. The same issue remains, zipline does not seem to be available/working.

    (zip35) C:\Users\chuam>zipline ingest -b quandl
    ‘zipline’ is not recognized as an internal or external command,
    operable program or batch file.

    The above is what I was given from the terminal. Not sure what is going on. Appreciate your advice. I have browsed through various forums the past one week but to no avail. Look forward to overcoming this. Thank you once again Andreas!

  18. Hello Andreas,
    Thank you very much for the book!
    I have a question for you, I have an API which gives me access to intraday data for futures and equities and I would like to have zipline connected to my API (which is from TradeStation).
    Could you please show me where I could find a guide for doing that? I am not a programmer and the chapter “Importing your data” in the book does not report the example.
    Thank you very much.

    Kind regards,
    Mark

  19. For the code in chapter 15, I keep getting AttributeError: ‘BundleData’ object has no attribute ‘equity_bar_reader’. This is after ingesting the random_futures_data bundle, editing the extensions.py file to register the bundle, and then patching the framework.

  20. Trying to use norgate data-zipline to implement your momentum 50 . but when I tried to get symbol(‘SPY’) or symbol(‘TLT’). it shows SymbolNotFound: Symbol ‘SPY’ was not found.

  21. Hi Andreas,

    Enjoying the book! I am using csi data, but having trouble reproducing results from the futures models (focusing on Time Return model since it is the simplest). Equity models are working fine.

    One issue at least is I have not been successful in creating a bundle with correct price_multiplier information. I have adapted the random_futures_bundle.py to include this in the metadata df and included a print(metadata) so I can see the info when I ingest. The print provides the correct price_multiplier. But for some reason running the Time Return model, the algo uses default price_multiplier = 1.0.

    Any idea how where the issue might be?

  22. Hi Anreas,

    Great book.
    Something I have always wanted to do. (Test systems with python)
    Now I am much much closer.
    Just wondering if you used norgate index constituents in back testing any models?
    I’m having some troubles but will try figure it out.

    • The Norgate Python API wasn’t ready in time, so i didn’t use that for the book. Their data is good though and I’m sure their support can figure it out for you.

    • Sam,

      Have you figured this one out yet? I’m having the same issues where the Norgate index constituents filters load an emply list into the function, and therefore return false for everything.

      • If you want worked examples from Trading Evoved that use Norgate Data’s capabilities (index constituents etc.) just contact us (Norgate).

        Happy to provide a zip file with Jupyter notebooks that show how it all works.

        It’s really quite neat.

  23. Im on page 106 – Your First Zipline Backtest

    When running the complete source code i downloaded, i run into these errors:

    Any one can point me to the direction to fix this? Thanks!

    —————————————————————————
    NameError Traceback (most recent call last)
    in ()
    71 handle_data=handle_data,
    72 capital_base=10000,
    —> 73 data_frequency = ‘daily’, bundle=’quandl’
    74 )

    C:\Users\Anaconda3\envs\zip35v2\lib\site-packages\zipline\utils\run_algo.py in run_algorithm(start, end, initialize, capital_base, handle_data, before_trading_start, analyze, data_frequency, data, bundle, bundle_timestamp, trading_calendar, metrics_set, default_extension, extensions, strict_extensions, environ, blotter)
    428 local_namespace=False,
    429 environ=environ,
    –> 430 blotter=blotter,
    431 )

    C:\Users\Anaconda3\envs\zip35v2\lib\site-packages\zipline\utils\run_algo.py in _run(handle_data, initialize, before_trading_start, analyze, algofile, algotext, defines, data_frequency, capital_base, data, bundle, bundle_timestamp, start, end, output, trading_calendar, print_algo, metrics_set, local_namespace, environ, blotter)
    157 trading_calendar=trading_calendar,
    158 trading_day=trading_calendar.day,
    –> 159 trading_days=trading_calendar.schedule[start:end].index,
    160 )
    161 first_trading_day =\

    C:\Users\Anaconda3\envs\zip35v2\lib\site-packages\zipline\finance\trading.py in __init__(self, load, bm_symbol, exchange_tz, trading_calendar, trading_day, trading_days, asset_db_path, future_chain_predicates, environ)
    101 trading_day,
    102 trading_days,
    –> 103 self.bm_symbol,
    104 )
    105

    C:\Users\Anaconda3\envs\zip35v2\lib\site-packages\zipline\data\loader.py in load_market_data(trading_day, trading_days, bm_symbol, environ)
    147 # date so that we can compute returns for the first date.
    148 trading_day,
    –> 149 environ,
    150 )
    151 tc = ensure_treasury_data(

    C:\Users\Anaconda3\envs\zip35v2\lib\site-packages\zipline\data\loader.py in ensure_benchmark_data(symbol, first_date, last_date, now, trading_day, environ)
    215
    216 try:
    –> 217 data = get_benchmark_returns(symbol)
    218 data.to_csv(get_data_filepath(filename, environ))
    219 except (OSError, IOError, HTTPError):

    C:\Users\Anaconda3\envs\zip35v2\lib\site-packages\zipline\data\benchmarks.py in get_benchmark_returns(symbol)
    21 Andreas Solution to side step the problem
    22 “””
    —> 23 cal = get_calendar(‘NYSE’)
    24 first_date = datetime(1930,1,1)
    25 last_date = datetime(2030,1,1)

    NameError: name ‘get_calendar’ is not defined

    • i managed to troubleshoot the issue. i’ve forgotten to import get_calendar when patching the benchmarks.py

      silly me.

  24. Hi, Andreas. I purchased your kindle book. It is a great one. Really like it. Appreciate your effort putting on the book.
    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.

  25. Jose Andres Riveros

    Hi Andreas and everybody, Im currently now installing as it says in page 100, Matplotlib and nb_conda in my zip35 enviroment. i was able to install Matplotlib but when i try to do the same with nb_conda im getting this error it seems there is come incompatibility about the versions but in im doing it in the zip35 enviroment as supposed to, no clue how to solve this one appreciate in advance any help regarding this issue.

    UnsatisfiableError: The following specifications were found
    to be incompatible with the existing python installation in your environment:

    – nb_conda -> python[version=’>=3.6,=3.7, nb_conda_kernels[version=’>=2.0.0′] -> notebook[version=’>=4.2.0′] -> terminado[version=’>=0.8.1′] -> pywinpty -> python[version=’>=3.6,=3.7, pip -> wheel -> setuptools
    python=3.5 -> pip -> wheel -> setuptools
    Package wheel conflicts for:
    python=3.5 -> pip -> wheel
    nb_conda -> nb_conda_kernels[version=’>=2.0.0′] -> notebook[version=’>=4.2.0′] -> terminado[version=’>=0.8.1′] -> pywinpty -> python[version=’>=3.6,=3.7, pip -> wheel
    Package pip conflicts for:
    python=3.5 -> pip
    nb_conda -> nb_conda_kernels[version=’>=2.0.0′] -> notebook[version=’>=4.2.0′] -> terminado[version=’>=0.8.1′] -> pywinpty -> python[version=’>=3.6,=3.7, pip
    Package colorama conflicts for:
    python=3.5 -> pip -> colorama
    nb_conda -> nb_conda_kernels[version=’>=2.0.0′] -> notebook[version=’>=4.2.0′] -> terminado[version=’>=0.8.1′] -> pywinpty -> python[version=’>=3.6,=3.7, pip -> colorama
    Package wincertstore conflicts for:
    python=3.5 -> pip -> wheel -> setuptools -> wincertstore[version=’>=0.2′]
    nb_conda -> nb_conda_kernels[version=’>=2.0.0′] -> notebook[version=’>=4.2.0′] -> terminado[version=’>=0.8.1′] -> pywinpty -> python[version=’>=3.6,=3.7, pip -> wheel -> setuptools -> wincertstore[version=’>=0.2′]
    Package certifi conflicts for:
    nb_conda -> nb_conda_kernels[version=’>=2.0.0′] -> notebook[version=’>=4.2.0′] -> terminado[version=’>=0.8.1′] -> pywinpty -> python[version=’>=3.6,=3.7, pip -> cachecontrol -> requests -> urllib3[version=’>=1.21.1,=1.21.1,=1.21.1, certifi
    python=3.5 -> pip -> cachecontrol -> requests -> urllib3[version=’>=1.21.1,=1.21.1,=1.21.1, certifi
    Package six conflicts for:
    nb_conda -> nb_conda_kernels[version=’>=2.0.0′] -> notebook[version=’>=4.2.0′] -> terminado[version=’>=0.8.1′] -> pywinpty -> python[version=’>=3.6,=3.7, pip -> cachecontrol -> requests -> urllib3[version=’>=1.21.1,=1.21.1,=1.21.1, pyopenssl[version=’>=0.14′] -> cryptography[version=’>=1.9,>=2.2.1′] -> six[version=’>=1.4.1′]
    python=3.5 -> pip -> cachecontrol -> requests -> urllib3[version=’>=1.21.1,=1.21.1,=1.21.1, pyopenssl[version=’>=0.14′] -> cryptography[version=’>=1.9,>=2.2.1′] -> six[version=’>=1.4.1′]

    not pretty sure what the issue is in here

    • Thomas N. Helget

      Jose:

      I had a similar problem with both matplotlib and nb_conda:

      UnsatisfiableError: The following specifications were found
      to be incompatible with the existing python installation in your environment:

      – matplotlib -> python[version=’>=2.7,=3.5,=3.6,=3.7, python[version=’>=2.7, pip
      nb_conda -> nb_conda_kernels[version=’>=2.0.0′] -> notebook[version=’>=4.2.0′] -> prometheus_client -> twisted -> service_identity[version=’>=18.1.0′] -> attrs[version=’>=16.0.0′] -> hypothesis -> enum34 -> python[version=’>=2.7, pip
      matplotlib -> numpy -> mkl_random[version=’>=1.0.2, mkl-service[version=’>=2, six -> python[version=’>=2.7,=3.5,=3.6,=3.7, pip
      Package wincertstore conflicts for:
      python=3.5 -> pip -> wheel -> setuptools -> wincertstore[version=’>=0.2′]
      nb_conda -> nb_conda_kernels[version=’>=2.0.0′] -> notebook[version=’>=4.2.0′] -> prometheus_client -> twisted -> service_identity[version=’>=18.1.0′] -> attrs[version=’>=16.0.0′] -> hypothesis -> enum34 -> python[version=’>=2.7, pip -> wheel -> setuptools -> wincertstore[version=’>=0.2′]
      matplotlib -> numpy -> mkl_random[version=’>=1.0.2, mkl-service[version=’>=2, six -> python[version=’>=2.7,=3.5,=3.6,=3.7, pip -> wheel -> setuptools -> wincertstore[version=’>=0.2′]
      Package colorama conflicts for:
      python=3.5 -> pip -> colorama
      nb_conda -> nb_conda_kernels[version=’>=2.0.0′] -> notebook[version=’>=4.2.0′] -> prometheus_client -> twisted -> service_identity[version=’>=18.1.0′] -> attrs[version=’>=16.0.0′] -> hypothesis -> enum34 -> python[version=’>=2.7, pip -> colorama
      matplotlib -> numpy -> mkl_random[version=’>=1.0.2, mkl-service[version=’>=2, six -> python[version=’>=2.7,=3.5,=3.6,=3.7, pip -> colorama
      Package six conflicts for:
      nb_conda -> nb_conda_kernels[version=’>=2.0.0′] -> notebook[version=’>=4.2.0′] -> prometheus_client -> twisted -> service_identity[version=’>=18.1.0′] -> attrs[version=’>=16.0.0′] -> hypothesis -> enum34 -> python[version=’>=2.7, pip -> cachecontrol -> requests -> urllib3[version=’>=1.21.1,=1.21.1, pyopenssl[version=’>=0.14′] -> cryptography[version=’>=1.9,>=2.2.1′] -> six[version=’>=1.4.1′]
      matplotlib -> numpy -> mkl_random[version=’>=1.0.2, mkl-service[version=’>=2, six
      python=3.5 -> pip -> cachecontrol -> requests -> urllib3[version=’>=1.21.1,=1.21.1, pyopenssl[version=’>=0.14′] -> cryptography[version=’>=1.9,>=2.2.1′] -> six[version=’>=1.4.1′]
      Package setuptools conflicts for:
      nb_conda -> nb_conda_kernels[version=’>=2.0.0′] -> notebook[version=’>=4.2.0′] -> prometheus_client -> twisted -> service_identity[version=’>=18.1.0′] -> attrs[version=’>=16.0.0′] -> hypothesis -> enum34 -> python[version=’>=2.7, pip -> wheel -> setuptools
      matplotlib -> numpy -> mkl_random[version=’>=1.0.2, mkl-service[version=’>=2, six -> python[version=’>=2.7,=3.5,=3.6,=3.7, pip -> wheel -> setuptools
      python=3.5 -> pip -> wheel -> setuptools
      Package wheel conflicts for:
      python=3.5 -> pip -> wheel
      nb_conda -> nb_conda_kernels[version=’>=2.0.0′] -> notebook[version=’>=4.2.0′] -> prometheus_client -> twisted -> service_identity[version=’>=18.1.0′] -> attrs[version=’>=16.0.0′] -> hypothesis -> enum34 -> python[version=’>=2.7, pip -> wheel
      matplotlib -> numpy -> mkl_random[version=’>=1.0.2, mkl-service[version=’>=2, six -> python[version=’>=2.7,=3.5,=3.6,=3.7, pip -> wheel
      Package certifi conflicts for:
      matplotlib -> numpy -> mkl_random[version=’>=1.0.2, mkl-service[version=’>=2, six -> python[version=’>=2.7,=3.5,=3.6,=3.7, pip -> cachecontrol -> requests -> urllib3[version=’>=1.21.1,=1.21.1, certifi
      python=3.5 -> pip -> cachecontrol -> requests -> urllib3[version=’>=1.21.1,=1.21.1, certifi
      nb_conda -> nb_conda_kernels[version=’>=2.0.0′] -> notebook[version=’>=4.2.0′] -> prometheus_client -> twisted -> service_identity[version=’>=18.1.0′] -> attrs[version=’>=16.0.0′] -> hypothesis -> enum34 -> python[version=’>=2.7, pip -> cachecontrol -> requests -> urllib3[version=’>=1.21.1,=1.21.1, certifi

  26. Thanks for the very informative book and for releasing the kindle version at such a reasonable price.

    Just for info I’ve managed to get the first zipline backtest (Chapter 7) working on Windows 10 using the stock Python 3.5 and pip and avoiding the need for anaconda (in case anyone was thinking of going that way and wondered if it was possible).

    Cheers,
    Jamie.

  27. Dear Andreas,

    Thank you for producing another great book! I have very much enjoyed reading all three of your books.

    I had trouble ingesting futures data into zipline (both your data, as well as my own). No errors were produced during ingestion, but when running an algorithm, switching from contract to contract did not work correctly. Regardless of roll method, Zipline was selecting the next contract in the order that it occurred in my file directory! In my case, for instance, it was rolling from March 2017 to March 2018, instead of to June 2018.

    The zipline docs could be better regarding futures ingestion, so I had to look through the zipline code, which was a bit complicated. As far as I can see, rather than checking all live contracts to determine which to roll to next, Zipline seems to only check the next unexpired SID in the list for a given symbol root and wait to roll that one. So if the contracts are out of order, there will be problems.

    A straightforward solution is to adjust your ingest code to sort the file directory list by a combined string of delivery year and delivery month (assuming they are included in the filename) before passing the list on to the rest of the code as normal. This appears to work as expected, but the Zipline library is quite complex and I could easily be missing something else. If you have any further info regarding custom futures ingestion, please advise!

    I hope this may help some of you other readers and save them some grief!

    Thanks again for producing such great books!.

    All the Best,
    Paul

    • Hey Paul, I think I might be running into a similar (the same) issue as you. I am trying to replicate the sample futures backtests that Andreas has in the book. With all of them, I am error’ing out with an issue stitching the continuous futures together, specially in the “roll_finder.py”.
      At the top of the error output:
      —–

      Exception ignored in: ‘zipline.assets.continuous_futures.OrderedContracts.contract_before_auto_close’
      AttributeError: ‘NoneType’ object has no attribute ‘next’

      —–
      But, specifically, at the end of the output:
      —–

      39 session = self.trading_calendar.minute_to_session_label(dt)
      40 front = oc.contract_before_auto_close(session.value)
      —>41 back = oc.contract_at_offset(front, 1, dt.value)
      42 if back is None:
      43 return front
      with the additional trailing detail:
      ~\zipline\assets\continuous_futures.pyx in zipline.assets.continuous_futures.OrderedContracts.contract_at_offset (zipline/assets\continuous_futures.c:7309)()

      ~\zipline\assets\continuous_futures.pyx in zipline.assets.continuous_futures.OrderedContracts.contract_at_offset (zipline/assets\continuous_futures.c:7061)()

      KeyError: 0

      —–
      Is this what you are encountering? I am completely stymied at this point and am wondering if I have found someone with the same problem! I’m continuing to work on this and will of course report any progress… would welcome anyone else’s too! Cheers

      • Hi Devon,

        I’m not sure if I got that error specifically, but I expect we had the same problem.

        When digging through that part of the Zipline code I couldn’t see where OrderedContracts actually did any ordering! It seemed to me that OrderedContracts expected the contracts to already be in order! But I could have missed something.

        Everything seems to be OK for me now once I made sure that I ingested the futures contracts in expiration order. Prior to that, most all of the functionality related to futures and continuous futures was not working properly. Of course, one must make all the changes that Andreas talks about in his book (constants.py for instance).

        If you have ordered the contracts and you are still having problems, feel free to let me know as I did make one or two other (presumably) minor changes to the ingest code during the process of solving this issue which seemingly didn’t make a difference to the outcome at the time, but may have actually played a role in fixing the issue.

        Best of luck!
        Paul

      • Hello Devon,

        I have the same issue as you, both in the Chapter 15 and Chapter 18 in the book. I tried much time to fix it according to the related methods here. But still can’t solve it.
        Could you provide the method if you make it clear of this problem ? Thank you very much.

        Best regards,
        Yong
        fluid@126.com

  28. Hi Paul, That’s interesting. I did find one minor issue in my setup (was calling up futures contracts that weren’t included in Andreas’ “random futures data” set (are you using this data source or another futures data source?) but after fixing that I am still at an impasse that is precluding me from completing my first futures backtest.
    For what it’s worth, at the top of the error output:
    —–

    IndexError Traceback (most recent call last)
    in ()
    218 capital_base=initial_portfolio_millions * 1000000,
    219 data_frequency = ‘daily’,
    –> 220 bundle=’random_futures_data’ )

    —–
    But, specifically, at the end of the output:
    —–

    ~\Anaconda3\envs\env_zipline\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
    1828
    1829 # validate the location
    -> 1830 self._is_valid_integer(key, axis)
    1831
    1832 return self._get_loc(key, axis=axis)

    ~\Anaconda3\envs\env_zipline\lib\site-packages\pandas\core\indexing.py in _is_valid_integer(self, key, axis)
    1711 l = len(ax)
    1712 if key >= l or key 1713 raise IndexError(“single positional indexer is out-of-bounds”)
    1714 return True
    1715

    IndexError: single positional indexer is out-of-bounds

    —–
    At this point, I’d be interested in your “minor changes” that you made. On a broader scale, I wonder if there is any interest in setting up a Google Group or something similar to allow for broader idea swapping… Anyways, cheers! Devon

  29. Hey Paul, I’m still stuck on my issue but, to your point re: ordered contracts, check out this thread, starting with the comment I’m posting here: https://github.com/quantopian/zipline/issues/2293#issuecomment-424337172

  30. Hello Andreas,

    first thank you for your books and contstant attention to everyone writing to you in this site.

    Iwanted to ask for your opinion on the following issue. I have done a 18 yr backtest on the strategy explained in “Stocks on the move” and as I read your latest book, “Trading Evolved”, you recall something that i saw while doing my backtest but could not find the way of fixing it on that moment, which is the following: how to deal with already nonexistent stocks. My backtest was done over more than 700 european stocks, so I am not limited to an index with the risk of trading only the current stocks and not the historical. But still I figure my backtest is “not-trading” some stocks that are no currently in the market anymore. How do you thta could be fixed or, do you think on such an ample stock base, would have had a very significant impact?

    thank you,

    Javier

  31. Hey Paul, would you mind sharing with the group the amendment you made to the code to get the futures bundle to properly ingest the underlying futures files in the appropriate (chronological) order? Many thanks!

  32. Hi Andreas, great book with a lot of insights! I am having however some problems populating the mysql database as per Chapter 24. I have a problem for the vals part of the insert statement where I get an error message saying that symbol and df are defined. Also get an error in the process symbol function but managed to fix it by changing data_location to data_path and importing tqdm_notebook from tqdm. Any help would be greatly appreciated. Thanks in advance

  33. Hi Andreas,

    In chapter 10, “Constructing ETF Models”, there is a bundle called ‘ac_equities_db’ in the code sample without further explanation. The name of the bundle suggests that this is a self-made Andreas C. bundle. I wonder what bundle the reader should use to run this code.

    Thanks for your help! Seb

    • Hi Sebastian,

      The ac_equities_db bundle is just the local bundle I used to run the code. It’s a custom bundle, based on my own local data. In the later chapters, you’ll read about how to make your own custom data to fit your local data.

  34. Hello everyone, I am trying to run the trend model from chapter 15. Managed to ingest the random_futures_data bundle as per chapter 23. However when running the model I get the following error. Any help would be greatly appreciated. Thanks in advance

    —————————————————————————
    KeyError Traceback (most recent call last)
    in ()
    311 capital_base=starting_portfolio,
    312 data_frequency = ‘daily’,
    –> 313 bundle=’random_futures_data’ )

    /Users/Redwall/anaconda3/envs/Zipline/lib/python3.5/site-packages/zipline/utils/run_algo.py in run_algorithm(start, end, initialize, capital_base, handle_data, before_trading_start, analyze, data_frequency, data, bundle, bundle_timestamp, trading_calendar, metrics_set, default_extension, extensions, strict_extensions, environ, blotter)
    428 local_namespace=False,
    429 environ=environ,
    –> 430 blotter=blotter,
    431 )

    /Users/Redwall/anaconda3/envs/Zipline/lib/python3.5/site-packages/zipline/utils/run_algo.py in _run(handle_data, initialize, before_trading_start, analyze, algofile, algotext, defines, data_frequency, capital_base, data, bundle, bundle_timestamp, start, end, output, trading_calendar, print_algo, metrics_set, local_namespace, environ, blotter)
    227 ).run(
    228 data,
    –> 229 overwrite_sim_params=False,
    230 )
    231

    /Users/Redwall/anaconda3/envs/Zipline/lib/python3.5/site-packages/zipline/algorithm.py in run(self, data, overwrite_sim_params)
    754 try:
    755 perfs = []
    –> 756 for perf in self.get_generator():
    757 perfs.append(perf)
    758

    /Users/Redwall/anaconda3/envs/Zipline/lib/python3.5/site-packages/zipline/gens/tradesimulation.py in transform(self)
    204 for dt, action in self.clock:
    205 if action == BAR:
    –> 206 for capital_change_packet in every_bar(dt):
    207 yield capital_change_packet
    208 elif action == SESSION_START:

    /Users/Redwall/anaconda3/envs/Zipline/lib/python3.5/site-packages/zipline/gens/tradesimulation.py in every_bar(dt_to_use, current_data, handle_data)
    132 metrics_tracker.process_commission(commission)
    133
    –> 134 handle_data(algo, current_data, dt_to_use)
    135
    136 # grab any new orders from the blotter, then clear the list.

    /Users/Redwall/anaconda3/envs/Zipline/lib/python3.5/site-packages/zipline/utils/events.py in handle_data(self, context, data, dt)
    214 context,
    215 data,
    –> 216 dt,
    217 )
    218

    /Users/Redwall/anaconda3/envs/Zipline/lib/python3.5/site-packages/zipline/utils/events.py in handle_data(self, context, data, dt)
    233 “””
    234 if self.rule.should_trigger(dt):
    –> 235 self.callback(context, data)
    236
    237

    in daily_trade(context, data)
    197 fields=[‘close’,’volume’],
    198 frequency=’1d’,
    –> 199 bar_count=250,
    200 )
    201

    /Users/Redwall/anaconda3/envs/Zipline/lib/python3.5/site-packages/zipline/_protocol.pyx in zipline._protocol.check_parameters.__call__.assert_keywords_and_call (zipline/_protocol.c:3747)()

    /Users/Redwall/anaconda3/envs/Zipline/lib/python3.5/site-packages/zipline/_protocol.pyx in zipline._protocol.BarData.history (zipline/_protocol.c:10190)()

    /Users/Redwall/anaconda3/envs/Zipline/lib/python3.5/site-packages/zipline/data/data_portal.py in get_history_window(self, assets, end_dt, bar_count, frequency, field, data_frequency, ffill)
    965 else:
    966 df = self._get_history_daily_window(assets, end_dt, bar_count,
    –> 967 field, data_frequency)
    968 elif frequency == “1m”:
    969 if field == “price”:

    /Users/Redwall/anaconda3/envs/Zipline/lib/python3.5/site-packages/zipline/data/data_portal.py in _get_history_daily_window(self, assets, end_dt, bar_count, field_to_use, data_frequency)
    804
    805 data = self._get_history_daily_window_data(
    –> 806 assets, days_for_window, end_dt, field_to_use, data_frequency
    807 )
    808 return pd.DataFrame(

    /Users/Redwall/anaconda3/envs/Zipline/lib/python3.5/site-packages/zipline/data/data_portal.py in _get_history_daily_window_data(self, assets, days_for_window, end_dt, field_to_use, data_frequency)
    827 field_to_use,
    828 days_for_window,
    –> 829 extra_slot=False
    830 )
    831 else:

    /Users/Redwall/anaconda3/envs/Zipline/lib/python3.5/site-packages/zipline/data/data_portal.py in _get_daily_window_data(self, assets, field, days_in_window, extra_slot)
    1115 days_in_window,
    1116 field,
    -> 1117 extra_slot)
    1118 if extra_slot:
    1119 return_array[:len(return_array) – 1, :] = data

    /Users/Redwall/anaconda3/envs/Zipline/lib/python3.5/site-packages/zipline/data/history_loader.py in history(self, assets, dts, field, is_perspective_after)
    547 dts,
    548 field,
    –> 549 is_perspective_after)
    550 end_ix = self._calendar.searchsorted(dts[-1])
    551

    /Users/Redwall/anaconda3/envs/Zipline/lib/python3.5/site-packages/zipline/data/history_loader.py in _ensure_sliding_windows(self, assets, dts, field, is_perspective_after)
    429 adj_dts = prefetch_dts
    430 prefetch_len = len(prefetch_dts)
    –> 431 array = self._array(prefetch_dts, needed_assets, field)
    432
    433 if field == ‘sid’:

    /Users/Redwall/anaconda3/envs/Zipline/lib/python3.5/site-packages/zipline/data/history_loader.py in _array(self, dts, assets, field)
    571 dts[0],
    572 dts[-1],
    –> 573 assets,
    574 )[0]
    575

    /Users/Redwall/anaconda3/envs/Zipline/lib/python3.5/site-packages/zipline/data/dispatch_bar_reader.py in load_raw_arrays(self, fields, start_dt, end_dt, sids)
    110 for i, asset in enumerate(assets):
    111 t = type(asset)
    –> 112 sid_groups[t].append(asset)
    113 out_pos[t].append(i)
    114

    KeyError:

  35. Hello, theres a kernel error in my Jupyter

    Traceback (most recent call last):
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\notebook\base\handlers.py”, line 516, in wrapper
    result = yield gen.maybe_future(method(self, *args, **kwargs))
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\tornado\gen.py”, line 1055, in run
    value = future.result()
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\tornado\concurrent.py”, line 238, in result
    raise_exc_info(self._exc_info)
    File “”, line 4, in raise_exc_info
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\tornado\gen.py”, line 1063, in run
    yielded = self.gen.throw(*exc_info)
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\notebook\services\sessions\handlers.py”, line 75, in post
    type=mtype))
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\tornado\gen.py”, line 1055, in run
    value = future.result()
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\tornado\concurrent.py”, line 238, in result
    raise_exc_info(self._exc_info)
    File “”, line 4, in raise_exc_info
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\tornado\gen.py”, line 1063, in run
    yielded = self.gen.throw(*exc_info)
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\notebook\services\sessions\sessionmanager.py”, line 79, in create_session
    kernel_id = yield self.start_kernel_for_session(session_id, path, name, type, kernel_name)
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\tornado\gen.py”, line 1055, in run
    value = future.result()
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\tornado\concurrent.py”, line 238, in result
    raise_exc_info(self._exc_info)
    File “”, line 4, in raise_exc_info
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\tornado\gen.py”, line 1063, in run
    yielded = self.gen.throw(*exc_info)
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\notebook\services\sessions\sessionmanager.py”, line 92, in start_kernel_for_session
    self.kernel_manager.start_kernel(path=kernel_path, kernel_name=kernel_name)
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\tornado\gen.py”, line 1055, in run
    value = future.result()
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\tornado\concurrent.py”, line 238, in result
    raise_exc_info(self._exc_info)
    File “”, line 4, in raise_exc_info
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\tornado\gen.py”, line 307, in wrapper
    yielded = next(result)
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\notebook\services\kernels\kernelmanager.py”, line 94, in start_kernel
    super(MappingKernelManager, self).start_kernel(**kwargs)
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\jupyter_client\multikernelmanager.py”, line 110, in start_kernel
    km.start_kernel(**kwargs)
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\jupyter_client\manager.py”, line 240, in start_kernel
    self.write_connection_file()
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\jupyter_client\connect.py”, line 547, in write_connection_file
    kernel_name=self.kernel_name
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\jupyter_client\connect.py”, line 212, in write_connection_file
    with secure_write(fname) as f:
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\contextlib.py”, line 59, in __enter__
    return next(self.gen)
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\jupyter_client\connect.py”, line 100, in secure_write
    win32_restrict_file_to_user(fname)
    File “C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\jupyter_client\connect.py”, line 53, in win32_restrict_file_to_user
    import win32api
    ImportError: No module named ‘win32api’

  36. Hi Andreas,

    Excellent book, thank you a lot for your effort to write this book as a practical manual, where readers can get hands dirty and code. This is the best way to learn!

    It’s very good you have written this book despite possible problems with installing zipline. There are not so many practical books and I think just because you decided to write about problematic topic you will get more readers.

    If there will be the next revision I would suggest:

    1) To introduce to readers more about open source community and how they can contribute and raising zipline relevant problems in github or asking help in stackoverflow. If they understand open source idea, instead of critics on your address, they can ask community to help and if they know where to ask for help, learning process will be less frustrating.

    2) To introduce code repo for the book to speed up learning and avoid rewriting all the code. Some books include links with password to the code repo. At the moment it takes a lot of time to rewrite the code from the book.

    3) I think there is not full code on the page 83-84 “The full code in one go would look like this right below.” I think “data = get_data(‘indexes’)” will not work…

    I’m just on the beginning of the book and I’m looking forward to read it further. Very good book and I definitely recommend the book to readers.

    Rg
    D

  37. Hi Andreas,

    I’ve just noticed in the book there is the link to zipline github so please edit my previous text and remove my comment about githug, but maybe for less experienced readers who have no idea about coding, stackoverflow and how to contribute could be usefull to mention…

    Rg
    D

  38. Hi Andreas,

    do you have an overview somewhere what your futures accronyms are? I’m interested in the commodity ones foe example [CL, HO, RB, NG, GC, LC, _C, _S, _W, SB, HG, CT, KC] ?

    • Hi Henning,

      All standard codes, with an underscore in front of single character codes.

      CL Crude
      HO Heating oil
      RB RBOB gasoline
      GC Gold
      LC Live cattle
      _C Corn
      _S Soybeans
      _W Wheat
      SB #11 sugar
      HG High grade copper
      CT Cotton
      KC Arabica coffee

  39. Wong Man Chun Manfred

    Dear Andreas,

    I am your reader for many years since your first book (Following the Trend) as well as your website got published years ago. You are the people who aspired me about systematic investment and fortunately I now have become an institutional fund manager for a Chicago based asset managers.

    I have recent bought your latest book and faced issue when installing zipline: Zipline Installation: failed with current_repodata.json. I fixed it by your provided solution (although I still want to know why we had to change the set_free_channel thing?)

    My current question is: As I finished installing zipline as well as creating the python 3.5 environment in Anaconda, as I tried installing Spyder (which is my preferred IDE) by directly clicking the “install” button in Anaconda Navigator, I am faced with the following warning that I do not how to solve:

    “python==3.3.6 cannot be installed on this environment. Do you want to install the package in an existing environment or….”

    I was expecting the Spyder to be installed and launched smoothly just like how I launched in the root environment (python 3.7).

    Please kindly advise and I very much look forward to your help after failing to fix it for a week.

    • Hi Manfred,

      I’ve seen this before with Anaconda.

      I think there’s a problem with Anaconda not resolving the environment correctly and forcing an upgrade of Python 3.5.

      Try doing:
      conda install spyder
      from a terminal in your Python 3.5 environment instead of clicking the GUI “Install” button.

      When I tried this a few weeks ago, it didn’t upgrade Python and seemed to work (i.e. I had Spyder, Zipline and Python 3.5 all operational in one environment).

      • Richard,

        It is so nice of you giving me a help on that. I read that as a solution from somewhere too. I tried yet it produced some weird messages about having some bugs or inconsistency. Although I could then launch spyder after that step, as spyder gets launched it has an error window (with a red cross). So this seems not perfect either….

        I know the book recommends using Jupyter. Yet even installing Jupyter from Anaconda in the python 3.5 environment still have the same problem. Have you heard of before? And which IDE do you use in following the book’s example if so under python 3.5?

      • Hi Manfred,

        It’s quite little sensitive to installation order in my experience.

        I’ve documented the environment exact environment I and installation steps plus patches I used here:
        https://pypi.org/project/norgatedata/

        scroll down to Zipline Limitations/Quirks.

  40. Any one with this issue in the first backtest? I’ve already ingested both quandl and the random_stock_data and neither are letting me backtest any ideas?

    AttributeError Traceback (most recent call last)
    in ()
    27 handle_data=handle_data,
    28 capital_base=10000,
    —> 29 data_frequency=’daily’,bundle=’quandl’
    30 )
    31

    C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\zipline\utils\run_algo.py in run_algorithm(start, end, initialize, capital_base, handle_data, before_trading_start, analyze, data_frequency, data, bundle, bundle_timestamp, trading_calendar, metrics_set, default_extension, extensions, strict_extensions, environ, blotter)
    428 local_namespace=False,
    429 environ=environ,
    –> 430 blotter=blotter,
    431 )

    C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\zipline\utils\run_algo.py in _run(handle_data, initialize, before_trading_start, analyze, algofile, algotext, defines, data_frequency, capital_base, data, bundle, bundle_timestamp, start, end, output, trading_calendar, print_algo, metrics_set, local_namespace, environ, blotter)
    157 trading_calendar=trading_calendar,
    158 trading_day=trading_calendar.day,
    –> 159 trading_days=trading_calendar.schedule[start:end].index,
    160 )
    161 first_trading_day =\

    C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\zipline\finance\trading.py in __init__(self, load, bm_symbol, exchange_tz, trading_calendar, trading_day, trading_days, asset_db_path, future_chain_predicates, environ)
    101 trading_day,
    102 trading_days,
    –> 103 self.bm_symbol,
    104 )
    105

    C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\zipline\data\loader.py in load_market_data(trading_day, trading_days, bm_symbol, environ)
    147 # date so that we can compute returns for the first date.
    148 trading_day,
    –> 149 environ,
    150 )
    151 tc = ensure_treasury_data(

    C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\zipline\data\loader.py in ensure_benchmark_data(symbol, first_date, last_date, now, trading_day, environ)
    215
    216 try:
    –> 217 data = get_benchmark_returns(symbol)
    218 data.to_csv(get_data_filepath(filename, environ))
    219 except (OSError, IOError, HTTPError):

    C:\Users\JAVIER\Anaconda3\envs\zipline_35\lib\site-packages\zipline\data\benchmarks.py in get_benchmark_returns(symbol)
    26 data=pd.DataFrame(0.0,index=dates,columns=[‘close’])
    27 data=[‘close’]
    —> 28 return data.sort_index().iloc[1:]
    29

    AttributeError: ‘list’ object has no attribute ‘sort_index’

  41. Hi Andreas. Thanks for publishing this book. I am stuck at page 102. When I launch Jupyter Notebook from my zip35 environment I get the following message in the terminal window:

    “Native kernel (python3) is not available”.

    Then when I go into Jupyter and try to do anything I get a series of error messages saying that the kernel has died and that automatic restart failed.

    Can you help? I’ve searched online without success.

    Thank you, Mike

  42. Hello everyone, I was wondering whether anybody has experienced the issue I detail below –

    My futures bundle ingested correctly from my database following was detailed in the book. I checked the sqlite files for how everything ended up mapping in zipline and all seemed to have worked fine.

    I have been following this post between Andreas and Jonathan Larkin (https://github.com/quantopian/zipline/issues/2293) as a guide for a possible solution to this problem as it was flagged by Andreas briefly in that post.

    My issue is as follows

    I ran a test backtest with a single root symbol [“AD”] over a 1 and a half year timeframe. The algo did nothing, but the setup seemed to be okay as the performance stats were all generated.

    I then delved into trying to access the data directly like Andreas and Jonathan have, and noticed that I am experiencing the same blank data in the continuous future object. I can access individual symbols via both their symbol and sid, but when the continuous contract object is instantiated it returns a blank dataframe with NaNs for OHLC data.

    Has anyone experienced this/found out why it may be occurring?

    • Jason,

      Incorrect symbology is the most likely culprit.

      • Thanks Richard,

        In particular do you mean symbology in terms of incorrect symbol format (i.e. not adhering to “xxMYY”), or something like a root symbol name creating an error or an incorrect expiry month? Or do you mean an incorrect ingest in terms of a field in one of the tables being left out?
        or all of the above?

        In any case I will test the data in my ingest script for all of those cases and anything else I can think of

  43. Hi Jason,

    Yes – I’m referring to the symbology xxMYY format that it uses to decode what to do. You might also want to ensure that all of the metadata fields are also populated too (asset_type, notice_date, expiration_date, auto_close_date, exchange, exchange_full, root_symbol, multiplier, start_date, end_date, first_traded too. I think ingestion order might also be important too – make sure the securities are ordered by delivery date.

    It took me a lot of frustrating effort (dozens of hours) with difficult-to-understand error messages and a lot of wild goose chases to write the zipline_norgatedata package, but I’m happy with the results now. With a few small changes I’m now futures trading systems testing back to 1970 too.

    Cheers,
    Richard.

    • excellent thank you Richard, massive help and extremely valuable to know where to focus my time. I took your advice to look at symbols and have had one success.

      For anyone following and future troubleshooters, I realized that I was importing the metadata table with my entire dataset worth of symbols (back to ~1960something) whereas the actual price data table was following a rule of ‘include in the SQL query if your end date is >= 2001-01-01.’

      I made the metadata table – and each symbol query when the individual OHLC lookup occurs – abide by the same logic and now my continuous futures contract for “AD” has populated itself with data. I have not yet checked whether it has rolled correctly. I suspect not as there are days with 0 volume toward the end of the dataset.. (set to roll=’volume’, adjustment=’mul’).

      I simply dumped a csv on my desktop of the data.history object to view this.

      This shows the value in having a community forum, I would absolutely have overlooked this issue..

  44. Hi, complete newbie here. I am up to page 96 on ‘Patching the Framework’ And I have no idea what to do. I can find the file Benchmark.py in my windows folders but I am confused as of what to do after that. Where do I create a new file? And where do I put the code in?
    This may be really obvious but I am stuck. If someone could explain this simply I would be very grateful…

    Thanks!
    Alan

    • Hi Alan,

      The objective of that page is to fabricate a DataFrame for the S&P500 benchmark index that zipline defaults to. The DataFrame that we’re creating spans from 1930-2030 and has 0s for prices. This is to circumvent a broken web data retrieval that is still programmed into Zipline. So open the file and replace the code that is currently in there with what Andreas has written on page 98. Then save it and close it, that’s all you need to do.

      The loader.py file is in the same folder as benchmarks, and there are a few lines that read as follows:

      if data is not None:
      return data.

      just ctrl + f and search for part of that code to find them as the doc is a few hundred lines long.

      these need to be commented out to read:
      “””if data is not None:
      return data”””

      This is how mine are currently set. Again save and close. They are small modifications.

      As for finding the Benchmarks.py file, mine is here: D:\DefaultLocation\Anaconda\envs\env_zipline\Lib\site-packages\zipline\data\Benchmarks.py. If it is not there, my suggestion would be to reinstall the Zipline library as it auto generates. Hope this help a bit.

  45. Hi all,

    Just wondering what is known regarding the order of ingest data for futures bundles and how this affects continuous futures objects. I have amended several strange behaviours such as data.history DataFrames with NaNs, incorrect prices for symbols, and strange rolling logic (0 or low volumes, etc.).

    I have fixed the obvious things and have cleaned up my ‘symbology’ as per what was mentioned above (lots of SQL queries to ensure my database has accurate and correct data, correct month codes/RRMYY convention, and making sure that my ingest script is formatting the data correctly and in the right tables), however cannot seem to return a data.history DataFrame that is 100% correct.

    My problems include unusual continuous futures rolling logic, and NaNs for part, but not all of the data.history dataframe.

    what has worked in my favour is ordering the data in my metadata and price data tables with the following logic in my SQL query prior to ingesting:

    ORDER BY blah.Root_Symbol ASC, blah.auto_close_date ASC;

    This has my E-mini S&P contract (crash test dummy) spitting out correct prices, volumes, and appearing to finally roll with the correct adjustment behaviour. Yet there are several months of price data missing from the dataframe.

    It is possible this is due to the following – the root symbol data only having quarterly contracts, or I’m still ordering something incorrectly, or there are likely a bunch of things I’m still doing wrong…

    has anyone encountered this before?

  46. I got the following error while trying to run the file Chapter 24 – Data and Databases/Populating Database.ipynb:
    NotSupportedError: (mysql.connector.errors.NotSupportedError) Authentication plugin ‘caching_sha2_password’ is not supported (Background on this error at: http://sqlalche.me/e/tw8g)

    Can anybody help me out of this?

    PS : While installing MySQL Community Edition the Python Connectors had failed to install. So I pip installed mysql-connector-python separately.

  47. I think the data in equity_history table is being inserted incorrectly. TICKER column is set as a unique ticker & because of the duplicate key update function the data is overwritten, finally inserting only single row for the ticker in the table.

    • For now I have dropped the idea of using a database. I am directly using csv files to ingest the bundle, as shown in chapter 23. Till now I am successfully able to run backtests. However I am wondering how do I periodically update the database say every day/week.

      For example, I have uploaded data till 25th Nov, 2019 & I want to now update data for 26th Nov.

      The obvious way is to append the csv files & run the zipline ingest -b random_stock_data function. But that is tricky & time consuming.
      Is there an easier way where I can just upload data for 26th Nov & not worry about the data that is uploaded till 25th Nov?
      How do you update your data bundle sir? @Andreas Clenow

      • You could always run a batch script scheduled to update as often as you like or at times when it’s convenient. I’m not aware of a simple way to do incremental ingest.

  48. Hi

    After a lot of effort i installed zipline since I managed to downgrade anaconda to 4.6.11.
    It was impressive for me that the version of zipline is 0.7 with no option for upgrade.

    After taking a look at the respective website i realised that version 1.3 works only in 64 bit OS.

    By the way i work in a Windows 7, 32 bit system.

    So no commands seem to work for me regarding zipline, like “”zipline ingest – b quandl”” where it is not recognised at all!

    Is there any solution for me or i have to format my pc to a 64 bit OS?

    *I am really disappointed because i have to stop reading waiting for an answer.

    Thanks!

    • Sorry you’re having issues, Chris. It’s impossible to predict and support all kinds of obsolete tech environments and I would strongly suggest to upgrade to modern software. Win7 is a decade old and even Microsoft stopped supporting it now, so it’s even a major security issue to run it at all. A 32 bit OS will limit you in all sort of ways, not the least that you’ll only be able to access 4gb memory.

  49. Panagiotis Troxidis

    While i have installed everything according to Trading.Evolved book i execute the command

    zipline ingest ? b quandl

    and the result is this:

    (zipline35) C:\Windows\system32>zipline ingest ? b quandl
    Traceback (most recent call last):
    File “c:\programdata\anaconda3\envs\zipline35\lib\runpy.py”, line 170, in _run
    module_as_main
    “main”, mod_spec)
    File “c:\programdata\anaconda3\envs\zipline35\lib\runpy.py”, line 85, in run
    code
    exec(code, run_globals)
    File “C:\ProgramData\Anaconda3\envs\zipline35\Scripts\zipline.exe_main.py”
    , line 5, in
    File “c:\programdata\anaconda3\envs\zipline35\lib\site-packages\zipline__init
    _.py”, line 23, in
    from . import data
    File “c:\programdata\anaconda3\envs\zipline35\lib\site-packages\zipline\data_
    init.py”, line 1, in
    from . import loader
    File “c:\programdata\anaconda3\envs\zipline35\lib\site-packages\zipline\data\l
    oader.py”, line 22, in
    from .benchmarks import get_benchmark_returns
    File “c:\programdata\anaconda3\envs\zipline35\lib\site-packages\zipline\data\b
    enchmarks.py”, line 16
    data = data[‘close’] return data.sort_index().iloc[1:]
    ^
    SyntaxError: invalid syntax

    Any idea on how can i get out of this?

    Thank you.

    • My guess here is that there’s a missing line break.

      This row looks odd:
      data = data[‘close’] return data.sort_index().iloc[1:]

      Should probably be two rows:
      data = data[‘close’]
      return data.sort_index().iloc[1:]

  50. Hello, I am really enjoying the book. I have worked through most of the errors and bugs so far but I am stuck on this one. I am getting the follow error:

    ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

    After googling this and trying a few different things I thought it could be a pandas compatibility issue but I am afraid to roll back my pandas and would not even know which version to roll back to. Any suggestions would be much appreciated. thanks so much

    2015-01-02 – Last Month Result: 0.00%
    C:\Users\Admin\Anaconda3\envs\zip35\lib\site-packages\numpy\lib\function_base.py:3103: RuntimeWarning: invalid value encountered in subtract
    X -= avg[:, None]
    C:\Users\Admin\Anaconda3\envs\zip35\lib\site-packages\scipy\stats\_distn_infrastructure.py:879: RuntimeWarning: invalid value encountered in greater
    return (self.a < x) & (x < self.b)
    C:\Users\Admin\Anaconda3\envs\zip35\lib\site-packages\scipy\stats\_distn_infrastructure.py:879: RuntimeWarning: invalid value encountered in less
    return (self.a < x) & (x < self.b)
    C:\Users\Admin\Anaconda3\envs\zip35\lib\site-packages\scipy\stats\_distn_infrastructure.py:1821: RuntimeWarning: invalid value encountered in less_equal
    cond2 = cond0 & (x <= self.a)
    Traceback (most recent call last):

    File "”, line 180, in
    bundle=’custom-csvdir-bundle’ )

    File “C:\Users\Admin\Anaconda3\envs\zip35\lib\site-packages\zipline\utils\run_algo.py”, line 430, in run_algorithm
    blotter=blotter,

    File “C:\Users\Admin\Anaconda3\envs\zip35\lib\site-packages\zipline\utils\run_algo.py”, line 229, in _run
    overwrite_sim_params=False,

    File “C:\Users\Admin\Anaconda3\envs\zip35\lib\site-packages\zipline\algorithm.py”, line 756, in run
    for perf in self.get_generator():

    File “C:\Users\Admin\Anaconda3\envs\zip35\lib\site-packages\zipline\gens\tradesimulation.py”, line 206, in transform
    for capital_change_packet in every_bar(dt):

    File “C:\Users\Admin\Anaconda3\envs\zip35\lib\site-packages\zipline\gens\tradesimulation.py”, line 134, in every_bar
    handle_data(algo, current_data, dt_to_use)

    File “C:\Users\Admin\Anaconda3\envs\zip35\lib\site-packages\zipline\utils\events.py”, line 216, in handle_data
    dt,

    File “C:\Users\Admin\Anaconda3\envs\zip35\lib\site-packages\zipline\utils\events.py”, line 235, in handle_data
    self.callback(context, data)

    File “”, line 161, in rebalance
    if ranking_table[security] > minimum_momentum:

    File “C:\Users\Admin\Anaconda3\envs\zip35\lib\site-packages\pandas\core\generic.py”, line 1121, in __nonzero__
    .format(self.__class__.__name__))

    ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Leave a Reply

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

*