赞
踩
量化交易的平台众多,从国外的Quantopian 到 国内的各种平台。 但对于刚入门的人来说,总是喜欢找到一种知根知底的offline的本地处理的方式。这样做的好处是特别灵活,同时不用被各种平台所限制。随心所欲的加上自己的算法,心情舒畅。
如果你也和我一样,那么就看下去吧。
操作系统:Win10 Python 环境:Anaconda Python 3.5 IDE:Pycharm 专业版(学生一年免费)
1.首先可以创建一个新的Python 环境。用于防止版本不兼容等问题同时方便环境管理。安装Anaconda最新版本后(我的是3.7),在开始搜索里找到你的Anaconda Promompt (Anaconda 3)。进入Anaconda Promompt 后,我们就可以用conda的脚本啦。
conda create -n env_zipline python=3.5
2. 然后用activate 命令激活环境
activate env_zipline
3. 在你(env_zipline)环境中安装 Zipline
conda install -c Quantopian zipline
https://www.zipline.io/install.html 详情请参照官方原文.
下面会介绍在Pycharm中或者其他环境中运行Zipline的demo栗子中会遇到的问题。
导入Quandl数据是我遇到的第一个问题。原因是官方给的方法不适合Win10且已经过时了。需要去quandl 去注册一个 账号,然后拿到你的token,来设置你的QUANDL_API_KEY 代替那串666。
- # 设置quandl的api key
- set QUANDL_API_KEY=66666666666666
-
- # 下载数据包
- zipline ingest -b quandl
有很多文章已经有详细说明,不赘述。参考引用文献 https://zhuanlan.zhihu.com/p/40565731
官方首先给出的是命令行的形式,如图一所示。但是我猜你一定不喜欢。
你也可以用 IPython Notebook,但是我也不喜欢。。所以我们就要用Pycharm+Zipline,因为我觉得调试起来很方便,debug的环境我比较熟悉。buyapple.py 修改后的demo程序代码如下,可以直接在pyhcarm中运行。主要使用的是 Zipline 中的 run_algorithm函数。
- from zipline.api import order, record, symbol
- from zipline.finance import commission, slippage
- from zipline import run_algorithm
- import pandas as pd
- def initialize(context):
- context.asset = symbol('AAPL')
- context.set_commission(commission.PerShare(cost=.0075, min_trade_cost=1.0))
- context.set_slippage(slippage.VolumeShareSlippage())
-
-
- def handle_data(context, data):
- order(context.asset, 10)
- record(AAPL=data.current(context.asset, 'price'))
-
- def analyze(context=None, results=None):
- import matplotlib.pyplot as plt
- # Plot the portfolio and asset data.
- ax1 = plt.subplot(211)
- results.portfolio_value.plot(ax=ax1)
- ax1.set_ylabel('Portfolio value (USD)')
- ax2 = plt.subplot(212, sharex=ax1)
- results.AAPL.plot(ax=ax2)
- ax2.set_ylabel('AAPL price (USD)')
-
- # Show the plot.
- plt.gcf().set_size_inches(18, 8)
- plt.show()
-
-
- def _test_args():
- """Extra arguments to use when zipline's automated tests run this example.
- """
- import pandas as pd
-
- return {
- 'start': pd.Timestamp('2014-01-01', tz='utc'),
- 'end': pd.Timestamp('2014-11-01', tz='utc'),
- }
-
-
- if __name__ == '__main__':
- capital_base = 200000
- start = pd.to_datetime('2015-01-01').tz_localize('US/Eastern')
- end = pd.to_datetime('2016-01-01').tz_localize('US/Eastern')
- result = run_algorithm(start=start, end=end, initialize=initialize,
- capital_base=capital_base, handle_data=handle_data,
- bundle='quandl', analyze=analyze)

你以为都好了吗,没有。测试的时候会调用benchmarks.py的文件来计算策略对比的一个基准。在 benchmarks.py 中使用了一个从 IEX 网站下载数据的链接,然而这个链接从19年就过期了。彻底的解决办法参考问题3.
错误入下所示。原因就是有一个SPY_benchmark.csv的文件需要从IEX的数据网站上下载,然而源码中的链接早已经不再支持。解决方法很多,比如可以在下载一个SPY_benchmark.csv放入对应的位置,文件可以在zipline的github中的resource文件夹中找到。我的放入位置为:C:UsersPro.ziplinedata,大家找到自己的对应位置即可。
下面给出一个相对正式的解决放法。
- Traceback (most recent call last):
- File "C:/Users/Pro/PycharmProjects/zipline_test/Buy_apple.py", line 62, in <module>
- bundle='quandl', analyze=analyze)
- File "C:UsersProAnaconda3envsenv_ziplinelibsite-packagesziplineutilsrun_algo.py", line 430, in run_algorithm
- blotter=blotter,
- File "C:UsersProAnaconda3envsenv_ziplinelibsite-packagesziplineutilsrun_algo.py", line 159, in _run
- trading_days=trading_calendar.schedule[start:end].index,
- File "C:UsersProAnaconda3envsenv_ziplinelibsite-packagesziplinefinancetrading.py", line 103, in __init__
- self.bm_symbol,
- File "C:UsersProAnaconda3envsenv_ziplinelibsite-packagesziplinedataloader.py", line 149, in load_market_data
- environ,
- File "C:UsersProAnaconda3envsenv_ziplinelibsite-packagesziplinedataloader.py", line 216, in ensure_benchmark_data
- data = get_benchmark_returns(symbol)
- File "C:UsersProAnaconda3envsenv_ziplinelibsite-packagesziplinedatabenchmarks.py", line 39, in get_benchmark_returns
- data = r.json()
- File "C:UsersProAnaconda3envsenv_ziplinelibsite-packagesrequestsmodels.py", line 897, in json
- return complexjson.loads(self.text, **kwargs)
- File "C:UsersProAnaconda3envsenv_ziplinelibjson__init__.py", line 319, in loads
- return _default_decoder.decode(s)
- File "C:UsersProAnaconda3envsenv_ziplinelibjsondecoder.py", line 339, in decode
- obj, end = self.raw_decode(s, idx=_w(s, 0).end())
- File "C:UsersProAnaconda3envsenv_ziplinelibjsondecoder.py", line 357, in raw_decode
- raise JSONDecodeError("Expecting value", s, err.value) from None
- json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

首先在IEX 网站上注册 https://iexcloud.io/ 得到你的个人的token。然后在 benchmarks.py的源文件中找到 request.get().如下图所示:
用你的token代替 pk_numbersnumbersnumbers。
- token = 'pk_numbersnumbersnumbers'
- r = requests.get(
- 'https://cloud.iexapis.com/stable/stock/{}/chart/5y?token={}'.format(symbol, token)
- )
详情请参见:https://github.com/quantopian/zipline/issues/2480
运行结果如下图所示
大家可以跑自己黑科技算法去做量化交易啦。接下来准备把框架的源程序看熟。我们一步步慢慢来。然后加上tushare的数据尝试做A股的数据分析。
最后我在我的github中上传了最后运行的文件:
https://github.com/szy1900/Zipline-Demo-Code-Run-in-Pycharmgithub.comhttps://www. zipline.io/beginner-tut orial.html#running-the-algorithm https:// github.com/quantopian/z ipline/issues/2480 https:// groups.google.com/forum /#!topic/zipline/X48PVjvbpFU https:// zhuanlan.zhihu.com/p/84 779129 https:// zhuanlan.zhihu.com/p/40 565731
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。