zipline icon indicating copy to clipboard operation
zipline copied to clipboard

Zipline beginner tutorial doesn't work

Open i-Data opened this issue 9 years ago • 5 comments

Environment

  • Operating System: (ubuntu 16.04 LTS)
  • Python Version: $ python --version 3
  • Python Bitness: $ python -c 'import math, sys;print(int(math.log(sys.maxsize + 1, 2) + 1))'
  • How did you install Zipline: (other (download))

Description of Issue

  • What did you expect to happen?
  • What happened instead?

I was trying to run the last tutorial here http://www.zipline.io/beginner-tutorial.html, got TypeError: a float is required

Here is how you can reproduce this issue on your machine: %load_ext zipline %%zipline --start 2000-1-1 --end 2014-1-1 -o perf_dma

from zipline.api import order_target, record, symbol, history import numpy as np

def initialize(context): context.i = 0

def handle_data(context, data): # Skip first 300 days to get full windows context.i += 1 if context.i < 300: return

# Compute averages
# history() has to be called with the same params
# from above and returns a pandas dataframe.
short_mavg = history(100, '1d', 'price').mean()
long_mavg = history(300, '1d', 'price').mean()

# Trading logic
if short_mavg[0] > long_mavg[0]:
    # order_target orders as many shares as needed to
    # achieve the desired number of shares.
    order_target(symbol('AAPL'), 100)
elif short_mavg[0] < long_mavg[0]:
    order_target(symbol('AAPL'), 0)

# Save values for later inspection
record(AAPL=data[symbol('AAPL')].price,
       short_mavg=short_mavg[0],
       long_mavg=long_mavg[0])

def analyze(context, perf): fig = plt.figure() ax1 = fig.add_subplot(211) perf.portfolio_value.plot(ax=ax1) ax1.set_ylabel('portfolio value in $')

ax2 = fig.add_subplot(212)
perf['AAPL'].plot(ax=ax2)
perf[['short_mavg', 'long_mavg']].plot(ax=ax2)

perf_trans = perf.ix[[t != [] for t in perf.transactions]]
buys = perf_trans.ix[[t[0]['amount'] > 0 for t in perf_trans.transactions]]
sells = perf_trans.ix[
    [t[0]['amount'] < 0 for t in perf_trans.transactions]]
ax2.plot(buys.index, perf.short_mavg.ix[buys.index],
         '^', markersize=10, color='m')
ax2.plot(sells.index, perf.short_mavg.ix[sells.index],
         'v', markersize=10, color='k')
ax2.set_ylabel('price in $')
plt.legend(loc=0)
plt.show()

below is the error output: /home/cheng/.local/lib/python3.5/site-packages/pandas/tseries/index.py:755: PerformanceWarning: Non-vectorized DateOffset being applied to Series or DatetimeIndex PerformanceWarning)

TypeError Traceback (most recent call last) in () ----> 1 get_ipython().run_cell_magic('zipline', '--start 2000-1-1 --end 2014-1-1 -o perf_dma', "\n\nfrom zipline.api import order_target, record, symbol, history\nimport numpy as np\n\ndef initialize(context):\n context.i = 0\n\n\ndef handle_data(context, data):\n # Skip first 300 days to get full windows\n context.i += 1\n if context.i < 300:\n return\n\n # Compute averages\n # history() has to be called with the same params\n # from above and returns a pandas dataframe.\n short_mavg = history(100, '1d', 'price').mean()\n long_mavg = history(300, '1d', 'price').mean()\n\n # Trading logic\n if short_mavg[0] > long_mavg[0]:\n # order_target orders as many shares as needed to\n # achieve the desired number of shares.\n order_target(symbol('AAPL'), 100)\n elif short_mavg[0] < long_mavg[0]:\n order_target(symbol('AAPL'), 0)\n\n # Save values for later inspection\n record(AAPL=data[symbol('AAPL')].price,\n short_mavg=short_mavg[0],\n long_mavg=long_mavg[0])\n\n\ndef analyze(context, perf):\n fig = plt.figure()\n ax1 = fig.add_subplot(211)\n perf.portfolio_value.plot(ax=ax1)\n ax1.set_ylabel('portfolio value in $')\n\n ax2 = fig.add_subplot(212)\n perf['AAPL'].plot(ax=ax2)\n perf[['short_mavg', 'long_mavg']].plot(ax=ax2)\n\n perf_trans = perf.ix[[t != [] for t in perf.transactions]]\n buys = perf_trans.ix[[t[0]['amount'] > 0 for t in perf_trans.transactions]]\n sells = perf_trans.ix[\n [t[0]['amount'] < 0 for t in perf_trans.transactions]]\n ax2.plot(buys.index, perf.short_mavg.ix[buys.index],\n '^', markersize=10, color='m')\n ax2.plot(sells.index, perf.short_mavg.ix[sells.index],\n 'v', markersize=10, color='k')\n ax2.set_ylabel('price in $')\n plt.legend(loc=0)\n plt.show()")

/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell) 2113 magic_arg_s = self.var_expand(line, stack_depth) 2114 with self.builtin_trap: -> 2115 result = fn(magic_arg_s, cell) 2116 return result 2117

/home/cheng/.local/lib/python3.5/site-packages/zipline/main.py in zipline_magic(line, cell) 267 '%s%%zipline' % ((cell or '') and '%'), 268 # don't use system exit and propogate errors to the caller --> 269 standalone_mode=False, 270 ) 271 except SystemExit as e:

/home/cheng/.local/lib/python3.5/site-packages/click/core.py in main(self, args, prog_name, complete_var, standalone_mode, **extra) 694 try: 695 with self.make_context(prog_name, args, **extra) as ctx: --> 696 rv = self.invoke(ctx) 697 if not standalone_mode: 698 return rv

/home/cheng/.local/lib/python3.5/site-packages/click/core.py in invoke(self, ctx) 887 """ 888 if self.callback is not None: --> 889 return ctx.invoke(self.callback, **ctx.params) 890 891

/home/cheng/.local/lib/python3.5/site-packages/click/core.py in invoke(*args, **kwargs) 532 with augment_usage_errors(self): 533 with ctx: --> 534 return callback(*args, **kwargs) 535 536 def forward(*args, **kwargs):

/home/cheng/.local/lib/python3.5/site-packages/click/decorators.py in new_func(*args, **kwargs) 15 """ 16 def new_func(*args, **kwargs): ---> 17 return f(get_current_context(), *args, **kwargs) 18 return update_wrapper(new_func, f) 19

/home/cheng/.local/lib/python3.5/site-packages/zipline/main.py in run(ctx, algofile, algotext, define, data_frequency, capital_base, bundle, bundle_timestamp, start, end, output, print_algo, local_namespace) 238 print_algo=print_algo, 239 local_namespace=local_namespace, --> 240 environ=os.environ, 241 ) 242

/home/cheng/.local/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, print_algo, local_namespace, environ) 178 ).run( 179 data, --> 180 overwrite_sim_params=False, 181 ) 182

/home/cheng/.local/lib/python3.5/site-packages/zipline/algorithm.py in run(self, data, overwrite_sim_params) 686 try: 687 perfs = [] --> 688 for perf in self.get_generator(): 689 perfs.append(perf) 690

/home/cheng/.local/lib/python3.5/site-packages/zipline/gens/tradesimulation.py in transform(self) 218 for dt, action in self.clock: 219 if action == BAR: --> 220 for capital_change_packet in every_bar(dt): 221 yield capital_change_packet 222 elif action == SESSION_START:

/home/cheng/.local/lib/python3.5/site-packages/zipline/gens/tradesimulation.py in every_bar(dt_to_use, current_data, handle_data) 131 perf_tracker.process_commission(commission) 132 --> 133 handle_data(algo, current_data, dt_to_use) 134 135 # grab any new orders from the blotter, then clear the list.

/home/cheng/.local/lib/python3.5/site-packages/zipline/utils/events.py in handle_data(self, context, data, dt) 182 context, 183 data, --> 184 dt, 185 ) 186

/home/cheng/.local/lib/python3.5/site-packages/zipline/utils/events.py in handle_data(self, context, data, dt) 201 """ 202 if self.rule.should_trigger(dt): --> 203 self.callback(context, data) 204 205

/home/cheng/.local/lib/python3.5/site-packages/zipline/algorithm.py in handle_data(self, data) 457 def handle_data(self, data): 458 if self._handle_data: --> 459 self._handle_data(self, data) 460 461 # Unlike trading controls which remain constant unless placing an

in handle_data(context, data)

/home/cheng/.local/lib/python3.5/site-packages/zipline/utils/api_support.py in wrapped(*args, **kwargs) 49 def wrapped(*args, **kwargs): 50 # Get the instance and call the method ---> 51 return getattr(get_algo_instance(), f.name)(*args, **kwargs) 52 # Add functor to zipline.api 53 setattr(zipline.api, f.name, wrapped)

/home/cheng/.local/lib/python3.5/site-packages/zipline/utils/api_support.py in wrapped_method(self, *args, **kwargs) 96 if not self.initialized: 97 raise exception ---> 98 return method(self, *args, **kwargs) 99 return wrapped_method 100 return decorator

/home/cheng/.local/lib/python3.5/site-packages/zipline/algorithm.py in history(self, bar_count, frequency, field, ffill) 2063 self._calculate_universe(), 2064 field, -> 2065 ffill 2066 ) 2067

/home/cheng/.local/lib/python3.5/site-packages/zipline/algorithm.py in get_history_window(self, bar_count, frequency, assets, field, ffill) 2074 frequency, 2075 field, -> 2076 ffill, 2077 ) 2078 else:

/home/cheng/.local/lib/python3.5/site-packages/zipline/data/data_portal.py in get_history_window(self, assets, end_dt, bar_count, frequency, field, ffill) 772 if field == "price": 773 df = self._get_history_daily_window(assets, end_dt, bar_count, --> 774 "close") 775 else: 776 df = self._get_history_daily_window(assets, end_dt, bar_count,

/home/cheng/.local/lib/python3.5/site-packages/zipline/data/data_portal.py in _get_history_daily_window(self, assets, end_dt, bar_count, field_to_use) 644 645 data = self._get_history_daily_window_data( --> 646 assets, days_for_window, end_dt, field_to_use 647 ) 648 return pd.DataFrame(

/home/cheng/.local/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) 672 assets, 673 field_to_use, --> 674 days_for_window[0:-1] 675 ) 676

/home/cheng/.local/lib/python3.5/site-packages/zipline/data/data_portal.py in _get_daily_window_for_sids(self, assets, field, days_in_window, extra_slot) 907 days_in_window, 908 field, --> 909 extra_slot) 910 if extra_slot: 911 return_array[:len(return_array) - 1, :] = data

/home/cheng/.local/lib/python3.5/site-packages/zipline/data/history_loader.py in history(self, assets, dts, field, is_perspective_after) 375 dts, 376 field, --> 377 is_perspective_after) 378 end_ix = self._calendar.get_loc(dts[-1]) 379 return hstack([window.get(end_ix) for window in block])

/home/cheng/.local/lib/python3.5/site-packages/zipline/data/history_loader.py in _ensure_sliding_windows(self, assets, dts, field, is_perspective_after) 278 if self._adjustments_reader: 279 adjs = self._get_adjustments_in_range( --> 280 asset, prefetch_dts, field, is_perspective_after) 281 else: 282 adjs = {}

/home/cheng/.local/lib/python3.5/site-packages/zipline/data/history_loader.py in _get_adjustments_in_range(self, asset, dts, field, is_perspective_after) 184 0, 185 0, --> 186 d[1]) 187 try: 188 adjs[adj_loc].append(mult)

/home/cheng/.local/lib/python3.5/site-packages/zipline/lib/adjustment.pyx in zipline.lib.adjustment.Float64Adjustment.init (zipline/lib/adjustment.c:5172)()

TypeError: a float is required

What steps have you taken to resolve this already?

i tried to run step by step, looks like something wrong with the method 'history', yeah?!

Please advise, much appreciated!

Sincerely, Cheng

i-Data avatar Dec 08 '16 10:12 i-Data

I had the same problem. This particular error is solved by changing the date to earlier date such as 2010. I think the bundle doesn't have dates so far in the past.

However the tutorial still doesn't work, the follow up error to this one for me is:

FileNotFoundError: [Errno 2] No such file or directory: '/home/j/.zipline/data/quantopian-quandl/2017-02-03T22;58;31.508525/minute_equities.bcolz/00/00/000000.bcolz/close/meta/sizes'

Tested on Windows 10 and a fresh VM of Mint 18.1 - both times with Conda.

According to Google it seems like this tutorial is bugged for more than a year now? Fix would be nice, I can give more details regarding the error.

ScJa avatar Feb 03 '17 23:02 ScJa

Hey @i-Data thanks for posting about this issue. I see from your stacktrace that you're running zipline with Python 3.5, which we don't yet support. You'll need to use zipline in a Python 2.7 or Python 3.4 environment (you can do this using conda or virtualenv).

@ScJa If you could open a separate issue and fill out the template then that'd be great!

freddiev4 avatar Mar 09 '17 17:03 freddiev4

I'm having same issue. Looks like every 6th day it fails. Mine is on python2.7.

UPDATE After realizing the code it's breaking on is on cpython compiled code, I started to suspect something was wrong with my library install. My previous install was on dokku which I have no idea what library gets installed. So i started from scratch on a native ubuntu 16.04, apt-get lnstall like from the official instructions. Everything seems to run smoothly so far.

UPDATE2 It runs for longer time period then eventually fails again..

  File "zipline/data/_adjustments.pyx", line 147, in zipline.data._adjustments.load_adjustments_from_sqlite (zipline/data/_adjustments.c:5849)
  File "zipline/data/_adjustments.pyx", line 225, in zipline.data._adjustments.load_adjustments_from_sqlite (zipline/data/_adjustments.c:4006)
TypeError: a float is required

quocgfy avatar Mar 10 '17 06:03 quocgfy

I've had the same problem with python 3.5 and these changes solved it for me.

  • Instead of history() I've used data.history() and passed in a list of securities as the first argument. The final moving average lines look like this:

long_mavg = data.history([symbol('AAPL')], 'price', 300, '1d').mean()

short_mavg = data.history([symbol('AAPL')], 'price', 100, '1d').mean()

  • I've also had to include import matplotlib.pyplot as plt after the zipline magic command for the charts to work.

rytsim avatar Apr 20 '17 11:04 rytsim

Merged the PR mentioned above to fix this 😃

freddiev4 avatar May 22 '17 19:05 freddiev4