0

我在 ubuntu 服务器上运行下面的测试代码。我正在尝试使用 zipline 回测一个简单的买入并持有策略。我只是想确保我已经正确安装了所有东西以进行回测。我对 zipline 很陌生。我收到以下错误,不知道为什么。

我正在按照此博客文章中的步骤进行操作:

https://towardsdatascience.com/introduction-to-backtesting-trading-strategies-7afae611a35e

我在 jupyter notebook 中运行代码。

当我之前运行代码以验证捆绑包已被摄取时,它显示的是:

代码:

!zipline bundles

输出:

apple-prices-2017-2019 2020-06-06 20:33:05.356288
apple-prices-2017-2019 2020-06-05 06:33:39.834841
apple-prices-2017-2019 2020-06-05 06:29:53.091904
apple-prices-2017-2019 2020-06-05 06:26:56.583051
csvdir <no ingestions>
quandl 2020-06-06 20:25:58.737940
quandl 2020-06-06 20:18:01.977412
quantopian-quandl 2020-06-04 16:15:57.717373
quantopian-quandl 2020-05-29 05:59:54.967114

下面是我在 jupyter notebook 中运行的代码以及错误。有没有人看到问题是什么,你能建议如何解决吗?

代码:

%%zipline --start 2016-1-1 --end 2017-12-31 --capital-base 1050.0 -o buy_and_hold.pkl

# imports
from zipline.api import order, symbol, record

# parameters
selected_stock = 'AAPL'
n_stocks_to_buy = 10

def initialize(context):
    context.has_ordered = False  

def handle_data(context, data):
    # record price for further inspection
    record(price=data.current(symbol(selected_stock), 'price'))

    # trading logic
    if not context.has_ordered:
        # placing order, negative number for sale/short
        order(symbol(selected_stock), n_stocks_to_buy)
        # setting up a flag for holding a position
        context.has_ordered = True

错误:

---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
<ipython-input-10-d11030c42e8b> in <module>()
----> 1 get_ipython().run_cell_magic('zipline', '--start 2016-1-1 --end 2017-12-31 --capital-base 1050.0 -o buy_and_hold.pkl', "\n# imports\nfrom zipline.api import order, symbol, record\n\n# parameters\nselected_stock = 'AAPL'\nn_stocks_to_buy = 10\n\ndef initialize(context):\n    context.has_ordered = False  \n\ndef handle_data(context, data):\n    # record price for further inspection\n    record(price=data.current(symbol(selected_stock), 'price'))\n    \n    # trading logic\n    if not context.has_ordered:\n        # placing order, negative number for sale/short\n        order(symbol(selected_stock), n_stocks_to_buy)\n        # setting up a flag for holding a position\n        context.has_ordered = True")

~/anaconda3/envs/py36/lib/python3.5/site-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
   2165             magic_arg_s = self.var_expand(line, stack_depth)
   2166             with self.builtin_trap:
-> 2167                 result = fn(magic_arg_s, cell)
   2168             return result
   2169 

~/anaconda3/envs/py36/lib/python3.5/site-packages/zipline/__main__.py in zipline_magic(line, cell)
    309             '%s%%zipline' % ((cell or '') and '%'),
    310             # don't use system exit and propogate errors to the caller
--> 311             standalone_mode=False,
    312         )
    313     except SystemExit as e:

~/anaconda3/envs/py36/lib/python3.5/site-packages/click/core.py in main(self, args, prog_name, complete_var, standalone_mode, **extra)
    780             try:
    781                 with self.make_context(prog_name, args, **extra) as ctx:
--> 782                     rv = self.invoke(ctx)
    783                     if not standalone_mode:
    784                         return rv

~/anaconda3/envs/py36/lib/python3.5/site-packages/click/core.py in invoke(self, ctx)
   1064         _maybe_show_deprecated_notice(self)
   1065         if self.callback is not None:
-> 1066             return ctx.invoke(self.callback, **ctx.params)
   1067 
   1068 

~/anaconda3/envs/py36/lib/python3.5/site-packages/click/core.py in invoke(*args, **kwargs)
    608         with augment_usage_errors(self):
    609             with ctx:
--> 610                 return callback(*args, **kwargs)
    611 
    612     def forward(*args, **kwargs):  # noqa: B902

~/anaconda3/envs/py36/lib/python3.5/site-packages/click/decorators.py in new_func(*args, **kwargs)
     19 
     20     def new_func(*args, **kwargs):
---> 21         return f(get_current_context(), *args, **kwargs)
     22 
     23     return update_wrapper(new_func, f)

~/anaconda3/envs/py36/lib/python3.5/site-packages/zipline/__main__.py in run(ctx, algofile, algotext, define, data_frequency, capital_base, bundle, bundle_timestamp, start, end, output, trading_calendar, print_algo, metrics_set, local_namespace, blotter)
    274         local_namespace=local_namespace,
    275         environ=os.environ,
--> 276         blotter=blotter,
    277     )
    278 

~/anaconda3/envs/py36/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)
    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/py36/lib/python3.5/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/py36/lib/python3.5/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/py36/lib/python3.5/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/py36/lib/python3.5/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/py36/lib/python3.5/site-packages/requests/models.py in json(self, **kwargs)
    894                     # used.
    895                     pass
--> 896         return complexjson.loads(self.text, **kwargs)
    897 
    898     @property

~/anaconda3/envs/py36/lib/python3.5/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/py36/lib/python3.5/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/py36/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)
4

1 回答 1

0

这篇文章解决了我的问题。只需要其中列出的前两个步骤。您需要更新 zipline/data 中的 benchmarks.py 和 loader.py 文件

获取 JSONDecodeError:期望值:使用 Python + Zipline + Docker + Jupyter 的第 1 行第 1 列(字符 0)

于 2020-06-06T22:33:12.770 回答