Pythonのバックテストフレームワーク「zipline」を使ってみる1 〜 環境構築

環境は次。

・JetBrains PyCharm Community Edition 2016.2.3
python 2.7.12
・zipline 1.0.2

今回実施するのは次

1.ziplineをpipを使ってインストールする
2.condaを使ってziplineをインストールする
2−1.AnacondaからMinicondaが必要なのでインストールする
2−2.Anacondaをインストールする
2−3.pycharmでziplineをインポートするコードを書いてみる
2−4.pycharmで使用するプロジェクトインタプリタをAnacondaのインストールの際にインストールされたpythonに変更する


1.ziplineをpipを使ってインストールする
pycharmでpipを使ってziplineをインストールする。
いきなりエラー。。。
lapack/blasが見つからないのが原因のようだ。

numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

proposed solutionに次のように書かれていた。

Try to run this command from the system terminal. Make sure that you use the correct version of 'pip' installed for your Python interpreter located at 'D:\Python27\python.exe'.

それならばと、Executed command「pip install --user zipline」をコマンドプロンプトで実行してみる。
すると最初に次の警告が出た。そのまま実行されたが、最後にエラーとなり失敗

You are using pip version 7.1.0, however version 9.0.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' comm
and.

なんだか面倒そうなので、方針変更。


2.condaを使ってziplineをインストールする
ziplineのドキュメントには次のように書かれている。

For windows, the easiest and best supported way to install zipline is to use Conda.
Once conda has been set up you can install Zipline from our Quantopian channel:

windowsでziplineをインストールするのに一番簡単で最適な方法はCondaを使うことらしい。
そして、一旦condaをセットアップしたら、QunatopianからZiplineをインストールできるとのこと。

さて、condaをインストールするにはここを見ろということで、この手順に従ってインストールする。

2−1.AnacondaからMinicondaが必要なのでインストールする
初めてCondaを始めるならAnacondaをインストールするのが良いと書かれていたので、Anacondaを使うことにする。

2−2.Anacondaをインストールする
Anacondaのページからダウンロードしてインストール。
インストールされたAnaconda Prompt上で「conda install -c Quantopian zipline」を実行したらインストール完了。

2−3.pycharmでziplineをインポートするコードを書いてみる
次のようにエラーとなる。pycharmからziplineを参照出来ていないことが原因。

始めたばかりで詳細が分からないので原因も不明だが、システム的にはそりゃそうだと経験的には納得出来る。
pycharmからanacondaがインストールした環境(ライブラリなど)を参照出来るようにすればいいのだけど、やり方が分からない。

2−4.pycharmで使用するプロジェクトインタプリタをAnacondaのインストールの際にインストールされたpythonに変更する
とりあえず、pycharmの「File→Settings→Project Interpreter」から使用するpythonをanacondaをインストールした際にインストールされたpythonに変更する。

すると次のようになり、ziplineのインポートに成功した。

order,record,symbolに赤線が引かれてエラーが出ているが、これはコードが間違っていた。
次のように「from zipline」を「from zipline.api」に変更してエラー無しとなった。

これで一通り導入までが完了。
※)正直、project interpreterを元のpythonからAnacondaでインストールしたpythonに変更したら、Available packagesに何も表示されなくなった。
※)「Anacondaよくわからない。」というブログにも書かれているのと同じ現象が起きたが、今回はziplineを使うことが目的なので、放置する。恐らくpythonについて基本的なところから勉強が必要だろう。。。


今回の内容は以上。
次回は、サンプルコードを動かそうと思う。
今のところ、以下の予定だけど、エラーが出てハマり中。。。

3.ziplineのサンプルコードを動かす
ziplineのドキュメントにチュートリアルがあり、そこに「My first algorithm」というタイトルで説明があるので、それを動かしてみる。
zipline.examplesというパッケージにbuyapple.pyというサンプルコードがあり、それを説明している。
buyapple.pyのコードを引用すると次のようになっている。

#!/usr/bin/env python
#
# Copyright 2014 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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'))


# Note: this function can be removed if running
# this algorithm on quantopian.com
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'),
    }

実行すると次のエラーが出て詰まっている。依存関係を考えなくても良いのがanacondaの良い点だと書いてあったのに!

ImportError: Missing required dependencies ['numpy']