Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example Code Error: name 'order_target' is not defined #2066

Closed
jasonchk opened this issue Dec 29, 2017 · 3 comments
Closed

Example Code Error: name 'order_target' is not defined #2066

jasonchk opened this issue Dec 29, 2017 · 3 comments

Comments

@jasonchk
Copy link

jasonchk commented Dec 29, 2017

Dear Zipline Maintainers,

Before I tell you about my issue, let me describe my environment:

Environment

  • Operating System: (Mac OS X High Sierra)
  • Python Version: Python 3.5.4 :: Anaconda, Inc.
  • Python Bitness: 64
  • How did you install Zipline: conda install -c quantopian zipline

Now that you know a little about me, let me tell you about the issue I am
having:

I tried the example code in http://www.zipline.io/beginner-tutorial.html

  • What did you expect to happen?
    I expected to see the backtesting result.

  • What happened instead?
    An error occurred.

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-7-ec1237a372dd> in <module>()
----> 1 get_ipython().run_cell_magic('zipline', '--start 2010-1-1 --end 2014-1-1', 'import matplotlib.pyplot as plt\nfrom zipline.api import symbol, order, record\n\ndef initialize(context):\n    context.i = 0\n    context.asset = symbol(\'AAPL\')\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    # data.history() has to be called with the same params\n    # from above and returns a pandas dataframe.\n    short_mavg = data.history(context.asset, \'price\', bar_count=100, frequency="1d").mean()\n    long_mavg = data.history(context.asset, \'price\', bar_count=300, frequency="1d").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(context.asset, 100)\n    elif short_mavg < long_mavg:\n        order_target(context.asset, 0)\n\n    # Save values for later inspection\n    record(AAPL=data.current(context.asset, \'price\'),\n           short_mavg=short_mavg,\n           long_mavg=long_mavg)\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()')

~/anaconda3/envs/crypto_p35/lib/python3.5/site-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
   2129             magic_arg_s = self.var_expand(line, stack_depth)
   2130             with self.builtin_trap:
-> 2131                 result = fn(magic_arg_s, cell)
   2132             return result
   2133 

~/anaconda3/envs/crypto_p35/lib/python3.5/site-packages/zipline/__main__.py in zipline_magic(line, cell)
    273             '%s%%zipline' % ((cell or '') and '%'),
    274             # don't use system exit and propogate errors to the caller
--> 275             standalone_mode=False,
    276         )
    277     except SystemExit as e:

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

~/anaconda3/envs/crypto_p35/lib/python3.5/site-packages/click/core.py in invoke(self, ctx)
    893         """
    894         if self.callback is not None:
--> 895             return ctx.invoke(self.callback, **ctx.params)
    896 
    897 

~/anaconda3/envs/crypto_p35/lib/python3.5/site-packages/click/core.py in invoke(*args, **kwargs)
    533         with augment_usage_errors(self):
    534             with ctx:
--> 535                 return callback(*args, **kwargs)
    536 
    537     def forward(*args, **kwargs):

~/anaconda3/envs/crypto_p35/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 

~/anaconda3/envs/crypto_p35/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 

~/anaconda3/envs/crypto_p35/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)
    177     ).run(
    178         data,
--> 179         overwrite_sim_params=False,
    180     )
    181 

~/anaconda3/envs/crypto_p35/lib/python3.5/site-packages/zipline/algorithm.py in run(self, data, overwrite_sim_params)
    707         try:
    708             perfs = []
--> 709             for perf in self.get_generator():
    710                 perfs.append(perf)
    711 

~/anaconda3/envs/crypto_p35/lib/python3.5/site-packages/zipline/gens/tradesimulation.py in transform(self)
    220             for dt, action in self.clock:
    221                 if action == BAR:
--> 222                     for capital_change_packet in every_bar(dt):
    223                         yield capital_change_packet
    224                 elif action == SESSION_START:

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

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

~/anaconda3/envs/crypto_p35/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 

~/anaconda3/envs/crypto_p35/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

<algorithm> in handle_data(context, data)

NameError: name 'order_target' is not defined

Here is how you can reproduce this issue on your machine:

Reproduction Steps

  1. Run the following code.
%%zipline --start 2010-1-1 --end 2014-1-1
import matplotlib.pyplot as plt
from zipline.api import symbol, order, record

def initialize(context):
    context.i = 0
    context.asset = symbol('AAPL')

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

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

    # Trading logic
    if short_mavg > long_mavg:
        # order_target orders as many shares as needed to
        # achieve the desired number of shares.
        order(context.asset, 100)
    elif short_mavg < long_mavg:
        order(context.asset, 0)

    # Save values for later inspection
    record(AAPL=data.current(context.asset, 'price'),
           short_mavg=short_mavg,
           long_mavg=long_mavg)
    
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()

...

What steps have you taken to resolve this already?

I replaced order_target with order and the code executed without error.
I have tried installing in another environment with Python 2.7 and still received the same issue.
Also checked the algorithm.py file and I can find the 'order_target_value' function.

Anything else?

Apologies for the text formatting above, especially the code sections. No idea why I can make them consistent.

Sincerely,
Jason

@freddiev4
Copy link
Contributor

freddiev4 commented Jan 1, 2018

Hi @jasonchk, just out of curiosity, can you try running the cell again with %%zipline --start 2014-1-1 --end 2018-1-1 or %%zipline --start 2014-1-1 --end 2017-1-1? You should be able to run a backtest up to 5 years ago from current day (x-ref #2031).

I'll see if I can reproduce your issue as well.

@jasonchk
Copy link
Author

jasonchk commented Jan 2, 2018

Hi @freddiev4 , I just realised that I haven't imported order_target from zipline.api. Sorry for the beginner mistake.

@jasonchk jasonchk closed this as completed Jan 2, 2018
@freddiev4
Copy link
Contributor

Ah no worries @jasonchk I missed that myself as well 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants