# Python 量化投資庫與平台引介
2017-12-14
[eclee](emailto:eclee92@gmail.com)

---
## 量化投資函式庫
+ [Popular Python Trading Platforms For Algorithmic Trading](https://www.quantinsti.com/blog/python-trading-library/)
+ [Python Backtesting Libraries For Quant Trading Strategies](https://robusttechhouse.com/python-backtesting-libraries-for-quant-trading-strategies/)
+ ...
---
## 量化投資社群平台
+ [Quantopian](https://www.quantopian.com)
+ [Github](https://github.com/quantopian/)
+ [[New] Phasing Out Brokerage Integrations](https://www.quantopian.com/posts/phasing-out-brokerage-integrations)
+ 賊賊的...轉向 [Zipline-Live 專案](http://www.zipline-live.io)
+ [[New] Quantopian Risk Model](https://www.quantopian.com/risk-model):這其實是 [Alphalens 專案](https://github.com/quantopian/alphalens) 的平台版
+ [New Tool For Quants: The Quantopian Risk Model](https://www.quantopian.com/posts/new-tool-for-quants-the-quantopian-risk-model)
+ 相關教學:
+ [Lecture 33 Factor Risk Exposure](https://www.quantopian.com/lectures/factor-risk-exposure)
+ [Lecture 34 Risk-Constrained Portfolio Optimization](https://www.quantopian.com/lectures/risk-constrained-portfolio-optimization)
+ [Risk Model Example: Detecting High Short Term Reversal Risk](https://www.quantopian.com/posts/risk-model-example-detecting-high-short-term-reversal-risk)
+ [https://www.quantopian.com/posts/introduction-to-the-quantopian-risk-model-in-research](https://www.quantopian.com/posts/introduction-to-the-quantopian-risk-model-in-research)
+ [QuantConnect](https://www.quantconnect.com/lean/)
+ The algorithmic trading engine of the future. Open source, Decentralized, Cloud-Hybrid Algorithmic Trading Engine.
+ 特色:
+ 支援 [C#](https://www.quantconnect.com/docs#csharp)、[Python](https://www.quantconnect.com/docs#python) 與 [F#](https://www.quantconnect.com/docs#fsharp) 三種語言
+ [可接券商 API 下單](https://www.quantconnect.com/docs#Supported-Brokerages)
+ [Github](https://github.com/QuantConnect/)
---
## Quantopian 引介
+ [引介:Stockfeel](https://www.stockfeel.com.tw/全球領先的python演算法交易平台─quantopian/)
+ [WEF (2015), The Future of Financial Services](http://www3.weforum.org/docs/WEF_The_future__of_financial_services.pdf)
+ [Quantopian 競賽](https://www.quantopian.com/open)
+ [winning algo drops below \$90K](https://www.quantopian.com/posts/winning-algo-drops-below-$90k)
---
## Quantopian 網路資源
+ 官方指引
+ [Python Lectures](https://www.quantopian.com/lectures)
+ [Getting Started](https://www.quantopian.com/tutorials/getting-started)
+ [Pipline](https://www.quantopian.com/tutorials/getting-started)
+ [Algorithmic Trading](https://www.quantopian.com/tutorials/algorithmic-trading-sentdex)
+ [Python for Finance with Zipline and Quantopian (sentdex)](https://www.youtube.com/playlist?list=PLQVvvaa0QuDeN06s5ervxTfTcVvt-xpZN)
+ [Getting Started with Futures](https://www.quantopian.com/tutorials/getting-started)
+ [API Reference](https://www.quantopian.com/help)
+ [教材:eclee's Github](https://github.com/eclee/Quantopian)
---
## Zipline 網路資源
+ [Zipline](http://www.zipline.io)
+ Zipline, a Pythonic Algorithmic Trading Library
+ [Github](https://github.com/quantopian/zipline)
+ [深入了解 zipline 回测框架 (含如何串接 CN 數據的深度教學)](https://rainx.gitbooks.io/-zipline/)
+ [Github: zipline-chinese](https://github.com/zhanghan1990/zipline-chinese)
+ zipline 是开源量化平台,但是当前zipline 并不支持A股的测试,很多在线平台如优矿,聚宽等都是基于zipline,本项目改进zipline,使得zipline支持A股测试
+ [Github: cn_zipline](https://github.com/JaysonAlbert/cn_zipline)
+ python tdx zipline bundles, 支持A股的zipline量化框架
+ [Zipline Live](http://www.zipline-live.io)
+ zipline-live is designed to be an extensible, drop-in replacement for zipline with multiple brokerage support to enable on premise trading of zipline algorithms.
+ [Github](https://github.com/zipline-live/zipline)
---
## Zipline 安裝 (目前支援 Python 2.7, 3.4 與 3.5)
以下操作在 CMD (Windows) 或 Terminal (Linux/Mac) 下操作
1. Python 安裝 (以下以 3.5 版為例,但建議 2.7 與 3.4 都自己嘗試安裝看看)
```
# 安裝 Python 3.5
conda create -n py35 python=3.5 anaconda
# 移除 Python 3.5 (如果 create 過程有誤)
conda remove -n py35 --all
# 查看目前存在的環境
conda info -e
```
2. 啟動與退出 Python (指定版次)
```
# 啟動指定的 Python 環境
activative py35 # for Widnows
source activate py35 # for Mac/Linux
# 退出特定的 Python 環境
deactivate
```
3. [安裝 Zipline](http://www.zipline.io/install.html)
```
$ pip install zipline
```
或
```
$ conda install -c Quantopian zipline
```
或
```
$ pip install git+https://github.com/quantopian/zipline.git
```
或 (EC 於 2018-1-8 測試可以成功,執行程式若有出現 SPY 錯誤訊息可以先不要理它)
```
pip install zipline --no-binary :all: --no-cache-dir
```
或
```
conda install -c quantopian/label/ci zipline
```
[移除 zipline](https://pip.pypa.io/en/stable/reference/pip_uninstall/)
```
pip uninstall zipline
```
或
```
conda uninstall zipline
```
4. 執行 jupyter notebook
```
cd MyPath # 切換到 MyPath (自訂的啟動路徑)
jupyter notebook # 啟動 jupter notebook
```
5. 將 [My First Algorithm 範例程式](http://www.zipline.io/beginner-tutorial.html#my-first-algorithm) 貼到 jupyter notebook 執行
Cell 1
```
%load_ext zipline
```
Cell 2
```
%%zipline --start 2000-1-1 --end 2014-1-1
from zipline.api import symbol, order, record
def initialize(context):
pass
def handle_data(context, data):
order(symbol('AAPL'), 10)
record(AAPL=data[symbol('AAPL')].price)
```
Cell 3
```
_.head()
```
Cell 4
```
%%zipline --start 2000-1-1 --end 2012-1-1 -o dma.pickle
from zipline.api import order_target, record, symbol
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_target(context.asset, 100)
elif short_mavg < long_mavg:
order_target(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()
```
4.
---
## zipline 與 zipline-live 的近期問題
+ Q:[quantopian/zipline » Can't connect to Yahoo - Errors: Loader: failed to cache the new benchmark returns](https://www.bountysource.com/issues/44723752-can-t-connect-to-yahoo-errors-loader-failed-to-cache-the-new-benchmark-returns)
+ Q:[Benchmark downloading is broken #1965](https://github.com/quantopian/zipline/issues/1965)
+ Q:[Unable to run zipline example with fresh install #2002](https://github.com/quantopian/zipline/issues/2002)
+ Q:[set_benchmark() does not work #2072](https://github.com/quantopian/zipline/issues/2072)
+ 解法 1-1:[Installing from GitHub](https://www.quantopian.com/posts/zipline-download)
```
$ pip install git+https://github.com/quantopian/zipline.git
```
+ 解法 1-2:[Installing from GitHub](https://github.com/quantopian/zipline/issues/2002)
```
$ git clone git@github.com:quantopian/zipline.git
$ pip install zipline/
```
+ 解法 2:[下載 benchmarks.txt 後,更名 benchmarks.py 替換掉原本套件安裝的](https://github.com/quantopian/zipline/files/1355002/benchmarks.txt)
+ 解法 3:[修改 benchmark 設定](https://github.com/quantopian/zipline/issues/1965)
```
from zipline.api import symbol, set_benchmark
def initialize(context):
set_benchmark(symbol("AAPL"))
```
---
##
+ []()
+ []()
+ []()
+ []()
---