【问题标题】:Zipline Installation Problems/ Trading Evolved First Backtest ErrorZipline 安装问题/交易演变的第一个回测错误
【发布时间】:2020-08-01 20:14:41
【问题描述】:

我一直在尝试正确安装 Zipline。我已按照 Andreas Clenow 书中第 7 章中的说明进行操作,但在第一个回测程序中遇到了问题。为了消除我的代码中的错误,我下载了应该可以工作的书籍代码。

%matplotlib inline

from zipline import run_algorithm
from zipline.api import order_target_percent,symbol

from datetime import datetime
import pytz

import matplotlib.pyplot as plt

#debug
import pandas as pd

def initialize(context):
    context.stock = symbol('AAPL')
    context.index_average_window = 100
    
def handle_data(context, data):
    equities_hist = data.history(context.stock, "close", 
                                 context.index_average_window, "1d")
    if equities_hist[-1] > equities_hist.mean():
        stock_weight = 1.0
    else:
        stock_weight = 0.0
    order_target_percent(context.stock, stock_weight)

def analyze(context, perf):
    fig = plt.figure(figsize=(12, 8))
    ax = fig.add_subplot(311)
    ax.set_title('Strategy Results')
    ax.semilogy(perf['portfolio_value'], linestyle='-', 
                label='Equity Curve', linewidth=3.0)
    ax.legend()
    ax.grid(False)
    ax = fig.add_subplot(312)
    ax.plot(perf['gross_leverage'], 
            label='Exposure', linestyle='-', linewidth=1.0)
    ax.legend()
    ax.grid(True)
    ax = fig.add_subplot(313)
    ax.plot(perf['returns'], label='Returns', linestyle='-.', linewidth=1.0)
    ax.legend()
    ax.grid(True)

start_date=datetime(1996,1,1,tzinfo=pytz.UTC)

end_date=datetime(2018,12,31,tzinfo=pytz.UTC)

results = run_algorithm(
    start=start_date, 
    end=end_date, 
    initialize=initialize, 
    analyze=analyze, 
    handle_data=handle_data, 
    capital_base=10000, 
    data_frequency='daily',
    bundle='quandl') 

我收到以下错误消息

AssertionError                            Traceback (most recent call last)
<ipython-input-8-b9def796232e> in <module>
      9     capital_base=10000,
     10     data_frequency='daily',
---> 11     bundle='quandl'
     12 ) 

~\Anaconda3202007\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, bundle, bundle_timestamp, trading_calendar, metrics_set, benchmark_returns, default_extension, extensions, strict_extensions, environ, blotter)
    405         environ=environ,
    406         blotter=blotter,
--> 407         benchmark_spec=benchmark_spec,
    408     )
    409 

~\Anaconda3202007\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, bundle, bundle_timestamp, start, end, output, trading_calendar, print_algo, metrics_set, local_namespace, environ, blotter, benchmark_spec)
    201                 trading_calendar=trading_calendar,
    202                 capital_base=capital_base,
--> 203                 data_frequency=data_frequency,
    204             ),
    205             metrics_set=metrics_set,

~\Anaconda3202007\envs\zip35\lib\site-packages\zipline\finance\trading.py in __init__(self, start_session, end_session, trading_calendar, capital_base, emission_rate, data_frequency, arena)
     36                  arena='backtest'):
     37 
---> 38         assert type(start_session) == pd.Timestamp
     39         assert type(end_session) == pd.Timestamp
     40 

AssertionError:

由于代码为作者工作,我还没有从 zipline 中得到任何工作代码,我认为这是一个安装问题。按照此链接上的 zipline 安装说明进行操作 https://pythonprogramming.net/zipline-local-install-python-programming-for-finance/我检查了Anaconda Navigator中应该需要的C包,发现wrapt、cython和cordereddict没有安装,通过AN安装。

我得到了完全相同的断言错误。

所以我想我会尝试使用上面 Py4fi 链接中不同的更简单的代码来测试安装。

%load_ext zipline
from zipline.api import order, record, symbol


def initialize(context):
    pass

def handle_data(context, data):
    order(symbol('AAPL'), 10)
    record(AAPL=data.current(symbol('AAPL'), 'price'))

%zipline --bundle quantopian-quandl --start 2000-1-1 --end 2012-1-1 -o backtest.pickle

在这种情况下,我收到以下错误:

NoBenchmark                               Traceback (most recent call last)
~\Anaconda3202007\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, bundle, bundle_timestamp, start, end, output, trading_calendar, print_algo, metrics_set, local_namespace, environ, blotter, benchmark_spec)
    215                 'algo_filename': getattr(algofile, 'name', '<algorithm>'),
--> 216                 'script': algotext,
    217             }

RunAlgoError: No ``benchmark_spec`` was provided, and ``zipline.api.set_benchmark`` was not called in ``initialize``.

顺便说一句 - 我在 Windows 上运行。

任何建议将不胜感激。

【问题讨论】:

    标签: python zipline


    【解决方案1】:

    为了让它工作,我必须做 3 件事,但我仍然收到运行时警告,但情节看起来不错。

    这些错误是否可能是由于没有安装所有正确的软件包造成的?

    没有。 1 - 解决断言错误——我在另一篇文章中发现了以下内容。 # 更改为 pd.Timestamp,因为 zipline 出现错误 #导入熊猫 将熊猫导入为 pd

    # Set start and end date
    # start_date=datetime(1996, 1, 1, tzinfo=pytz.UTC)
    # end_date=datetime(2018, 12, 31, tzinfo=pytz.UTC)
    
    start_date = pd.Timestamp('1996-1-1', tz='utc')
    # changed to 303272018 as data does not exist past this
    end_date = pd.Timestamp('2018-03-27', tz='utc')
    

    没有。 2 - 然后我回到基准错误,我将 set_benchmark 添加到初始化函数以消除错误

    # added this to get benchmark spec error to go away
    # tried SPY but apparently this is not a symbol in the quandl bundle
    zipline.api.set_benchmark(symbol('AAPL'))
    

    没有。 3. - 必须将结束日期更改为 0/3/27/2018,因为 quandl 数据不会到 2018 年 12 月 31 日

    # changed to 303272018 as data does not exist past this
    end_date = pd.Timestamp('2018-03-27', tz='utc')
    

    警告信息

    C:\Users\tbrug\Anaconda3202007\envs\zip35\lib\site-packages\empyrical\stats.py:711: RuntimeWarning: 在 true_divide 中遇到无效值 出=出, C:\Users\tbrug\Anaconda3202007\envs\zip35\lib\site-packages\empyrical\stats.py:797: RuntimeWarning: 在 true_divide 中遇到无效值 np.divide(average_annual_return, Annualized_downside_risk, out=out)

    【讨论】:

      【解决方案2】:

      我遇到了和你一样的问题。

      忽略警告。您可以在笔记本顶部添加以下内容:

      import warnings
      warnings.filterwarnings('ignore')
      

      【讨论】:

        【解决方案3】:

        将 start_date 从“1996-1-1”更改为以后的日期,例如'2004-4-1'。 将 end_date 从 '2018-12-31' 更改为更早的日期,例如'2018-3-27'。

        然后两个“RuntimeWarning: invalid value遇到true_divide...”消失。

        【讨论】:

          【解决方案4】:

          Zipline 正在运行其从 Quandl => bundle='quandl' 加载股票价格的回测。

          您需要在 Quandl 创建一个免费帐户并设置您的 API 密钥:

          import os
          os.environ['QUANDL_API_KEY'] = 'you_api_key_here'
          

          然后执行:

          !zipline bundles
          !zipline ingest -b quantopian-quandl
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-10-21
            • 2013-12-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-01-14
            相关资源
            最近更新 更多