ValueError with AAPL dual moving average example
Running the example file will throw a ValueError exception.
AAPL
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-17-d3e7421e3071> in <module>()
----> 1 get_ipython().run_cell_magic(u'zipline', u'--start 2001-6-1 --end 2012-1-1 --symbols AAPL -o perf_dma', u"\nfrom zipline.api import order_target, record, symbol, history, add_history\nimport numpy as np\n\ndef initialize(context):\n # Register 2 histories that track daily prices, \n # one with a 100 window and one with a 300 day window\n add_history(100, '1d', 'price')\n add_history(300, '1d', 'price')\n \n context.i = 0\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 > long_mavg:\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 < long_mavg:\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 \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/python2.7/dist-packages/IPython/core/interactiveshell.pyc in run_cell_magic(self, magic_name, line, cell)
2230 magic_arg_s = self.var_expand(line, stack_depth)
2231 with self.builtin_trap:
-> 2232 result = fn(magic_arg_s, cell)
2233 return result
2234
/root/zipline/zipline/utils/cli.pyc in parse_cell_magic(line, cell)
126 output_var_name = args.pop('output', None)
127
--> 128 perf = run_pipeline(print_algo=False, algo_text=cell, **args)
129
130 if output_var_name is not None:
/root/zipline/zipline/utils/cli.pyc in run_pipeline(print_algo, **kwargs)
190 capital_base=float(kwargs['capital_base']))
191
--> 192 perf = algo.run(source)
193
194 output_fname = kwargs.get('output', None)
/root/zipline/zipline/algorithm.pyc in run(self, source, overwrite_sim_params, benchmark_return_source)
421 # perf dictionary
422 perfs = []
--> 423 for perf in self.gen:
424 perfs.append(perf)
425
/root/zipline/zipline/gens/tradesimulation.pyc in transform(self, stream_in)
125 date,
126 snapshot,
--> 127 self.algo.instant_fill,
128 )
129 # Perf messages are only emitted if the snapshot contained
/root/zipline/zipline/gens/tradesimulation.pyc in _process_snapshot(self, dt, snapshot, instant_fill)
212
213 if any_trade_occurred:
--> 214 new_orders = self._call_handle_data()
215 for order in new_orders:
216 self.algo.perf_tracker.process_event(order)
/root/zipline/zipline/gens/tradesimulation.pyc in _call_handle_data(self)
234 during the call.
235 """
--> 236 self.algo.handle_data(self.current_data)
237 orders = self.algo.blotter.new_orders
238 self.algo.blotter.new_orders = []
/root/zipline/zipline/algorithm.pyc in handle_data(self, data)
224 self.history_container.update(data, self.datetime)
225
--> 226 self._handle_data(self, data)
227
228 def analyze(self, perf):
<string> in handle_data(context, data)
/usr/local/lib/python2.7/dist-packages/pandas/core/generic.pyc in __nonzero__(self)
690 raise ValueError("The truth value of a {0} is ambiguous. "
691 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
--> 692 .format(self.__class__.__name__))
693
694 __bool__ = __nonzero__
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
It's telling you that the comparison it's trying to do is actually comparing two Series.
Change the comparisons as follows:
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)
Then it will work fine.
Basically, the history variables aren't just the value, so you need to index out the value. It's not just a numpy mean() you're seeing there.
Regards, Ken
PS first post on github,.. not sure if I can or should be the one to close the issue.
Hello Ken,
Shouldn’t the indexing be [-1] to access the most recent value i.e.
if short_mavg[-1] > long_mavg[-1]: # order_target orders as many shares as needed to # achieve the desired number of shares. order_target(symbol('AAPL'), 100) elif short_mavg[-1] < long_mavg[-1]: order_target(symbol('AAPL'), 0)
P.
From: kenhersey [mailto:[email protected]] Sent: 25 July 2014 04:32 To: quantopian/zipline Subject: Re: [zipline] ValueError with AAPL dual moving average example (#377)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
It's telling you that the comparison it's trying to do is actually comparing two Series.
Change the comparisons as follows:
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)
Then it will work fine.
Basically, the history variables aren't just the value, so you need to index out the value. It's not just a numpy mean() you're seeing there.
Regards, Ken
— Reply to this email directly or view it on GitHub https://github.com/quantopian/zipline/issues/377#issuecomment-50104748 . https://github.com/notifications/beacon/2846421__eyJzY29wZSI6Ik5ld3NpZXM6QmVhY29uIiwiZXhwaXJlcyI6MTcyMTg3ODM0NSwiZGF0YSI6eyJpZCI6Mzc4OTQyMDh9fQ==--e810d48faac6421d452aa1283843de8d59de17cd.gif
Hi Peter! You may be right. I was oscillating between the two options and perhaps decided wrong! I took the final cue from the record statement.
I haven't used history yet like you.
Now that the syntax is correct, I'm sure someone else will chime in to confirm on the logic to finalize.
Thanks!!
Sent from my iPhone
On Jul 25, 2014, at 5:57 AM, pcawthron [email protected] wrote:
Hello Ken,
Shouldn’t the indexing be [-1] to access the most recent value i.e.
if short_mavg[-1] > long_mavg[-1]:
order_target orders as many shares as needed to
achieve the desired number of shares.
order_target(symbol('AAPL'), 100) elif short_mavg[-1] < long_mavg[-1]: order_target(symbol('AAPL'), 0)
P.
From: kenhersey [mailto:[email protected]] Sent: 25 July 2014 04:32 To: quantopian/zipline Subject: Re: [zipline] ValueError with AAPL dual moving average example (#377)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
It's telling you that the comparison it's trying to do is actually comparing two Series.
Change the comparisons as follows:
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)
Then it will work fine.
Basically, the history variables aren't just the value, so you need to index out the value. It's not just a numpy mean() you're seeing there.
Regards, Ken
— Reply to this email directly or view it on GitHub https://github.com/quantopian/zipline/issues/377#issuecomment-50104748 . https://github.com/notifications/beacon/2846421__eyJzY29wZSI6Ik5ld3NpZXM6QmVhY29uIiwiZXhwaXJlcyI6MTcyMTg3ODM0NSwiZGF0YSI6eyJpZCI6Mzc4OTQyMDh9fQ==--e810d48faac6421d452aa1283843de8d59de17cd.gif — Reply to this email directly or view it on GitHub.
Hello Ken,
I'm entirely unsure now. I can run the old version of the Dual MA example but I don't get any output with the 'history' one. Also I hadn't noticed thar 'record' was indexing th 0th element. This is the working version I made my assumption on:
#!/usr/bin/env python
#
# Copyright 2013 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import matplotlib.pyplot as plt
from zipline.algorithm import TradingAlgorithm
from zipline.utils.factory import load_from_yahoo
import numpy as np
# Import exponential moving average from talib wrapper
from zipline.transforms.ta import EMA
from datetime import datetime
import pytz
class DualEMATaLib(TradingAlgorithm):
"""Dual Moving Average Crossover algorithm.
This algorithm buys apple once its short moving average crosses
its long moving average (indicating upwards momentum) and sells
its shares once the averages cross again (indicating downwards
momentum).
"""
def initialize(self, short_window=20, long_window=40):
# Add 2 mavg transforms, one with a long window, one
# with a short window.
self.short_ema_trans = EMA(timeperiod=short_window)
self.long_ema_trans = EMA(timeperiod=long_window)
# To keep track of whether we invested in the stock or not
self.invested = False
def handle_data(self, data):
self.short_ema = self.short_ema_trans.handle_data(data)
self.long_ema = self.long_ema_trans.handle_data(data)
if self.short_ema is None or self.long_ema is None:
return
self.buy = False
self.sell = False
if self.short_ema[-1] > self.long_ema[-1] and not self.invested:
self.order('AAPL', 100)
self.invested = True
self.buy = True
elif self.short_ema[-1] < self.long_ema[-1] and self.invested:
self.order('AAPL', -100)
self.invested = False
self.sell = True
self.record(AAPL=data['AAPL'].price,
short_ema=self.short_ema['AAPL'],
long_ema=self.long_ema['AAPL'],
buy=self.buy,
sell=self.sell)
if __name__ == '__main__':
start = datetime(1990, 1, 1, 0, 0, 0, 0, pytz.utc)
end = datetime(1991, 1, 1, 0, 0, 0, 0, pytz.utc)
data = load_from_yahoo(stocks=['AAPL'], indexes={}, start=start,
end=end)
dma = DualEMATaLib()
results = dma.run(data).dropna()
fig = plt.figure()
ax1 = fig.add_subplot(211, ylabel='portfolio value')
results.portfolio_value.plot(ax=ax1)
ax2 = fig.add_subplot(212)
results[['AAPL', 'short_ema', 'long_ema']].plot(ax=ax2)
ax2.plot(results.ix[results.buy].index, results.short_ema[results.buy],
'^', markersize=10, color='m')
ax2.plot(results.ix[results.sell].index, results.short_ema[results.sell],
'v', markersize=10, color='k')
plt.legend(loc=0)
plt.gcf().set_size_inches(18, 8)
plt.show()