Python Zipline安装问题/首次反向测试错误

Python Zipline安装问题/首次反向测试错误,python,zipline,Python,Zipline,我一直在尝试正确安装拉链。我已按照第7章中的说明进行操作。Andreas Clenow的书,并在第一个回溯测试程序中遇到问题。为了消除我的代码中的错误,我下载了本应该可以工作的代码 %matplotlib inline from zipline import run_algorithm from zipline.api import order_target_percent,symbol from datetime import datetime import pytz import ma

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

%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:
在这种情况下,我得到以下错误:

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``.
NoBenchmark回溯(最近一次调用)
~\anaconda320007\envs\zip35\lib\site packages\zipline\utils\run\u algo.py in\u run(处理数据、初始化、交易开始前、分析、algofile、algotext、定义、数据频率、资本基数、捆绑包、捆绑包时间戳、开始、结束、输出、交易日历、打印算法、度量集、本地名称空间、环境、记事本、基准规范)
215“algo_文件名”:getattr(algo文件名,'',''),
-->216“脚本”:文本,
217             }
RunAlgoError:未提供“基准测试规范”,并且在“初始化”中未调用“zipline.api.set\u benchmark”。
顺便说一句,我正在Windows上运行


如果您有任何建议,我将不胜感激。

为了让这项功能发挥作用,我必须做3件事,但我仍然收到运行时警告,但绘图看起来不错

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

第一,为了解决断言错误,我在另一篇文章中发现了以下内容。 #更改为pd。时间戳,因为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添加到initialize函数中以消除错误

# 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'))
第三Had必须将截止日期更改为2018年3月27日,因为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\anaconda320007\envs\zip35\lib\site packages\empyric\stats.py:711:RuntimeWarning:true\u divide中遇到无效值 out=out, C:\Users\tbrug\anaconda320007\envs\zip35\lib\site packages\empyric\stats.py:797:RuntimeWarning:true\u divide中遇到无效值
np.除法(平均年回报率,年化下行风险,out=out)

我遇到了和你一样的问题

不要理会这些警告。您可以在笔记本顶部包括以下内容:

import warnings
warnings.filterwarnings('ignore')

将开始日期从“1996-1-1”更改为更晚的日期,例如“2004-4-1”。 将结束日期从“2018-12-31”更改为更早的日期,例如“2018-3-27”


然后两个“RuntimeWarning:在true_divide中遇到无效值…”消失。

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

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

import os
os.environ['QUANDL_API_KEY'] = 'you_api_key_here'
然后执行:

!zipline bundles
!zipline ingest -b quantopian-quandl
!zipline bundles
!zipline ingest -b quantopian-quandl