PyAlgoTradeの日本語解説ブログ

PyAlgoTrade の勝手に日本語解説ブログ。日本語の内容に関して保証はいたしておりません。必ず本家のサイトをご確認ください。

2015年9月2日水曜日

PyAlgoTrade をCentOS7にインストールしたときの環境設定に関するメモ 2015年版

昨日までPyAlgoTradeを一通り動かしたところで、別のマシンへの再インストールの予感がする。
正直言って1コアのバーチャルマシンでは全然パワー不足、パラメータの組み合わせにより試行回数は莫大になるから仕方ないよね。
豪華なマシンはレンタルサーバーだと高いので、自宅マシンにインストールすることになりそうだ。不要なマシンを次々とインストールするので作業手順が必要。

CentOS7 上で環境を作った時のメモを残す。実行はrootユーザーで行う
ちなみにマシンは最低2Gのメモリがないとインストール途中で止まる。

 vi /etc/sysconfig/selinux で SELINUX=disabledに変更して再起動
 yum -y  groupinstall "Development tools"
 yum -y  install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel
 curl -kL https://bootstrap.pypa.io/get-pip.py |python
 pip install virtualenv
 yum -y  install readline-devel
 yum -y  install python-numpy python-scipy
 yum -y  install numpy
 yum -y  install libpng-devel
 yum -y  install png
 yum -y  install pandas scikit gdata
 yum -y  install libgdata
 yum -y  install python-devel
 pip install numpy pandas  matplotlib
 pip install pyalgotrade
 vi /usr/lib64/python2.7/site-packages/pyalgotrade/plotter.py でグラフの吐き出し先を変更できるようにする

PyAlgoTradeが出力するグラフの出力先を変更したい



ここまで入れれば、他の分析ツールを入れるのは簡単

 pip install zipline
 pip install pybacktest
 yum -y  install atlas-devel
 pip install QSTK
 yum -y  install numpy-f2py
 yum -y  install gcc-gfortran
 pip install QSTK

ついでにhttpdとかphpとかrubyを入れておくと、データーを公開するときに便利

 yum -y  install httpd
 yum -y  install ruby
 yum -y  install gem
 gem install jpstock
 yum -y  install mariadb mariadb-server
 systemctl start mariadb.service
 yum -y  --enablerepo=remi,epel,rpmforge install php-mbstring

2015/9では以上の手順でインストールできた。この先は保証しない。
たぶんDockerでイメージを作ればいいと思うけど、それは今度にしよう。

2015年9月1日火曜日

PyAlgoTrade のチュートリアルをかいつまんで訳す その4 チャート表示

文字だけではわかりにくい。
PyAlgoは超簡単にチャートに出力できるから

以下のプログラムをsma_crossover.pyとして保存

from pyalgotrade import strategy
from pyalgotrade.technical import ma
from pyalgotrade.technical import cross


class SMACrossOver(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument, smaPeriod):
        strategy.BacktestingStrategy.__init__(self, feed)
        self.__instrument = instrument
        self.__position = None
        # We'll use adjusted close values instead of regular close values.
        self.setUseAdjustedValues(True)
        self.__prices = feed[instrument].getPriceDataSeries()
        self.__sma = ma.SMA(self.__prices, smaPeriod)

    def getSMA(self):
        return self.__sma

    def onEnterCanceled(self, position):
        self.__position = None

    def onExitOk(self, position):
        self.__position = None

    def onExitCanceled(self, position):
        # If the exit was canceled, re-submit it.
        self.__position.exitMarket()

    def onBars(self, bars):
        # If a position was not opened, check if we should enter a long position.
        if self.__position is None:
            if cross.cross_above(self.__prices, self.__sma) > 0:
                shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())
                # Enter a buy market order. The order is good till canceled.
                self.__position = self.enterLong(self.__instrument, shares, True)
        # Check if we have to exit the position.
        elif not self.__position.exitActive() and cross.cross_below(self.__prices, self.__sma) > 0:
            self.__position.exitMarket()

以下のプログラムを違うファイル名で保存

from pyalgotrade import plotter
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.stratanalyzer import returns
import sma_crossover

# Load the yahoo feed from the CSV file
feed = yahoofeed.Feed()
feed.addBarsFromCSV("orcl", "orcl-2000.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = sma_crossover.SMACrossOver(feed, "orcl", 20)

# Attach a returns analyzers to the strategy.
returnsAnalyzer = returns.Returns()
myStrategy.attachAnalyzer(returnsAnalyzer)

# Attach the plotter to the strategy.
plt = plotter.StrategyPlotter(myStrategy)
# Include the SMA in the instrument's subplot to get it displayed along with the closing prices.
plt.getInstrumentSubplot("orcl").addDataSeries("SMA", myStrategy.getSMA())
# Plot the simple returns on each bar.
plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())

# Run the strategy.
myStrategy.run()
myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())

# Plot the strategy.
plt.plot()

最初のサンプルで使ったorcl-2000.csv はここでも必要。ローカルディレクトリに置いておく
これを実行した結果以下のようにプロットされるはず

linuxのデスクトップ以外でこれを動かすと以下のようなエラーが出て止まる。
** (main.py:23150): WARNING **: Could not open X display
(main.py:23150): Gdk-CRITICAL **: gdk_cursor_new_for_display: assertion 'GDK_IS_DISPLAY (display)' failed

画像ファイルに吐き出す。 ライブラリの改造が必要

PyAlgoTradeが出力するグラフの出力先を変更したい

もちろん呼び出すほうも改造が必要、matplotlibをplotterより先にimportするのがコツ。あとはplotを呼び出すときにファイル名を指定する



import matplotlib
matplotlib.use('Agg')
from pyalgotrade import plotter
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.stratanalyzer import returns
import sma_crossover

# Load the yahoo feed from the CSV file
feed = yahoofeed.Feed()
feed.addBarsFromCSV("orcl", "orcl-2000.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = sma_crossover.SMACrossOver(feed, "orcl", 20)

# Attach a returns analyzers to the strategy.
returnsAnalyzer = returns.Returns()
myStrategy.attachAnalyzer(returnsAnalyzer)

# Attach the plotter to the strategy.
plt = plotter.StrategyPlotter(myStrategy)
# Include the SMA in the instrument's subplot to get it displayed along with the closing prices.
plt.getInstrumentSubplot("orcl").addDataSeries("SMA", myStrategy.getSMA())
# Plot the simple returns on each bar.
plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())

# Run the strategy.
myStrategy.run()
myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())

# Plot the strategy.
plt.plot(None,None,"test.png")

以下3行を書き換えました
最初の2行
 import matplotlib
 matplotlib.use('Agg')
最後の1行
 plt.plot(None,None,"test.png")

PyAlgoTrade のチュートリアルをかいつまんで訳す その3 最適化

オプティマイザを使いましょう。アイデアは非常に簡単です:


  • 担当する1つのサーバがあります:
  • 戦略を実行するためのBarを提供します。
  • 戦略を実行するためのパラメータを提供します。
  • ワーカーのそれぞれの戦略の結果を記録します。
  • 担当する複数のワーカーがいます。
  • サーバが提供するバーやパラメータを使用して戦略を実行します。


これらを説明するために、我々はRSI2として知られている戦略を使用します
(http://stockcharts.com/school/doku.php?id=chart_school:trading_strategies:rsi2)


  • トレンドを識別するための単純移動平均期間。この市場参入を単純移動平均150と250の間の範囲で試します。
  • 出口点に対してより小さい単純移動平均期間。この脱出を単純移動平均5と15の間の範囲で試します。。
  • ショート/ロング・ポジションの両方を入力するためのRSI期間。このrsiPeriodを2と10の間の範囲で試します。
  • ロングポジションエントリのRSI売られ過ぎのしきい値。我々は、このoverSoldThresholdを5と25の範囲で試します。
  • ショートポジションエントリのRSI買わしきい値。我々は、このoverBoughtThresholdを75と95の間の範囲で試します。

私の数学がOKであれば、それらは4409559異なる組み合わせです。

パラメータの一組のためにこの戦略をテストすることは私には約0.16秒を要しました。
すべての組み合わせを実行するために、約8.5日かかります。
それは長い時間ですが、8コアのコンピュータを得ることができるならば、合計時間は約2.5時間まで減らすことができます。
手っ取り早く言うと、並列演算が必要です。



「ダウ・ジョーンズ工業株平均」の毎日のバーの3年をダウンロードして起動してみましょう:

python -c "from pyalgotrade.tools import yahoofinance; yahoofinance.download_daily_bars('dia', 2009, 'dia-2009.csv')"
python -c "from pyalgotrade.tools import yahoofinance; yahoofinance.download_daily_bars('dia', 2010, 'dia-2010.csv')"
python -c "from pyalgotrade.tools import yahoofinance; yahoofinance.download_daily_bars('dia', 2011, 'dia-2011.csv')"
rsi2.pyとして以下のコードを保存します。
from pyalgotrade import strategy
from pyalgotrade.technical import ma
from pyalgotrade.technical import rsi
from pyalgotrade.technical import cross


class RSI2(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument, entrySMA, exitSMA, rsiPeriod, overBoughtThreshold, overSoldThreshold):
        strategy.BacktestingStrategy.__init__(self, feed)
        self.__instrument = instrument
        # We'll use adjusted close values, if available, instead of regular close values.
        if feed.barsHaveAdjClose():
            self.setUseAdjustedValues(True)
        self.__priceDS = feed[instrument].getPriceDataSeries()
        self.__entrySMA = ma.SMA(self.__priceDS, entrySMA)
        self.__exitSMA = ma.SMA(self.__priceDS, exitSMA)
        self.__rsi = rsi.RSI(self.__priceDS, rsiPeriod)
        self.__overBoughtThreshold = overBoughtThreshold
        self.__overSoldThreshold = overSoldThreshold
        self.__longPos = None
        self.__shortPos = None

    def getEntrySMA(self):
        return self.__entrySMA

    def getExitSMA(self):
        return self.__exitSMA

    def getRSI(self):
        return self.__rsi

    def onEnterCanceled(self, position):
        if self.__longPos == position:
            self.__longPos = None
        elif self.__shortPos == position:
            self.__shortPos = None
        else:
            assert(False)

    def onExitOk(self, position):
        if self.__longPos == position:
            self.__longPos = None
        elif self.__shortPos == position:
            self.__shortPos = None
        else:
            assert(False)

    def onExitCanceled(self, position):
        # If the exit was canceled, re-submit it.
        position.exitMarket()

    def onBars(self, bars):
        # Wait for enough bars to be available to calculate SMA and RSI.
        if self.__exitSMA[-1] is None or self.__entrySMA[-1] is None or self.__rsi[-1] is None:
            return

        bar = bars[self.__instrument]
        if self.__longPos is not None:
            if self.exitLongSignal():
                self.__longPos.exitMarket()
        elif self.__shortPos is not None:
            if self.exitShortSignal():
                self.__shortPos.exitMarket()
        else:
            if self.enterLongSignal(bar):
                shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())
                self.__longPos = self.enterLong(self.__instrument, shares, True)
            elif self.enterShortSignal(bar):
                shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())
                self.__shortPos = self.enterShort(self.__instrument, shares, True)

    def enterLongSignal(self, bar):
        return bar.getPrice() > self.__entrySMA[-1] and self.__rsi[-1] <= self.__overSoldThreshold

    def exitLongSignal(self):
        return cross.cross_above(self.__priceDS, self.__exitSMA) and not self.__longPos.exitActive()

    def enterShortSignal(self, bar):
        return bar.getPrice() < self.__entrySMA[-1] and self.__rsi[-1] >= self.__overBoughtThreshold

    def exitShortSignal(self):
        return cross.cross_below(self.__priceDS, self.__exitSMA) and not self.__shortPos.exitActive()

サーバーのスクリプトは以下になります。
import itertools
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.optimizer import server


def parameters_generator():
    instrument = ["dia"]
    entrySMA = range(150, 251)
    exitSMA = range(5, 16)
    rsiPeriod = range(2, 11)
    overBoughtThreshold = range(75, 96)
    overSoldThreshold = range(5, 26)
    return itertools.product(instrument, entrySMA, exitSMA, rsiPeriod, overBoughtThreshold, overSoldThreshold)

# The if __name__ == '__main__' part is necessary if running on Windows.
if __name__ == '__main__':
    # Load the feed from the CSV files.
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV("dia", "dia-2009.csv")
    feed.addBarsFromCSV("dia", "dia-2010.csv")
    feed.addBarsFromCSV("dia", "dia-2011.csv")

    # Run the server.
    server.serve(feed, parameters_generator(), "localhost", 5000)

サーバーのコードは3つのことを行っています。
組み合わせストラテジーの異なるパラメータの生成
CSVファイルからフィードをダウンロード
サーバーを実行してローカル接続port5000で待ち受け

ワーカースクリプトを実行して待ち受けているサーバーを呼び出します。
from pyalgotrade.optimizer import worker
import rsi2

# The if __name__ == '__main__' part is necessary if running on Windows.
if __name__ == '__main__':
    worker.run(rsi2.RSI2, "localhost", 5000, workerName="localworker")

コンソールを2つ開いて、サーバーのスクリプトを実行した後、別のコンソールでワーカーを実行する それぞれの出力は以下のようなになる。 サーバー
2014-05-03 15:04:01,083 server [INFO] Loading bars
2014-05-03 15:04:01,348 server [INFO] Waiting for workers
2014-05-03 15:04:58,277 server [INFO] Partial result 1242173.28754 with parameters: ('dia', 150, 5, 2, 91, 19) from localworker
2014-05-03 15:04:58,566 server [INFO] Partial result 1203266.33502 with parameters: ('dia', 150, 5, 2, 81, 19) from localworker
2014-05-03 15:05:50,965 server [INFO] Partial result 1220763.1579 with parameters: ('dia', 150, 5, 3, 83, 24) from localworker
2014-05-03 15:05:51,325 server [INFO] Partial result 1221627.50793 with parameters: ('dia', 150, 5, 3, 80, 24) from localworker
.
.
ワーカー
2014-05-03 15:02:25,377 localworker [INFO] Running strategy with parameters ('dia', 150, 5, 2, 94, 5)
2014-05-03 15:02:25,661 localworker [INFO] Result 1090481.06342
2014-05-03 15:02:25,661 localworker [INFO] Result 1031470.23717
2014-05-03 15:02:25,662 localworker [INFO] Running strategy with parameters ('dia', 150, 5, 2, 93, 25)
2014-05-03 15:02:25,665 localworker [INFO] Running strategy with parameters ('dia', 150, 5, 2, 84, 14)
2014-05-03 15:02:25,995 localworker [INFO] Result 1135558.55667
2014-05-03 15:02:25,996 localworker [INFO] Running strategy with parameters ('dia', 150, 5, 2, 93, 24)
2014-05-03 15:02:26,006 localworker [INFO] Result 1083987.18174
2014-05-03 15:02:26,007 localworker [INFO] Running strategy with parameters ('dia', 150, 5, 2, 84, 13)
2014-05-03 15:02:26,256 localworker [INFO] Result 1093736.17175
2014-05-03 15:02:26,257 localworker [INFO] Running strategy with parameters ('dia', 150, 5, 2, 84, 12)
2014-05-03 15:02:26,280 localworker [INFO] Result 1135558.5566


一つのサーバーで複数のワーカーを走らせたほうがいい。というか1ワーカーだとものすごく待つ。

サーバーではなくデスクトップ機で並列演算をさせたいのであれば、 pyalgotrade.optimizer.local モジュールを使いましょう。


import itertools
from pyalgotrade.optimizer import local
from pyalgotrade.barfeed import yahoofeed
import rsi2


def parameters_generator():
    instrument = ["dia"]
    entrySMA = range(150, 251)
    exitSMA = range(5, 16)
    rsiPeriod = range(2, 11)
    overBoughtThreshold = range(75, 96)
    overSoldThreshold = range(5, 26)
    return itertools.product(instrument, entrySMA, exitSMA, rsiPeriod, overBoughtThreshold, overSoldThreshold)


# The if __name__ == '__main__' part is necessary if running on Windows.
if __name__ == '__main__':
    # Load the feed from the CSV files.
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV("dia", "dia-2009.csv")
    feed.addBarsFromCSV("dia", "dia-2010.csv")
    feed.addBarsFromCSV("dia", "dia-2011.csv")

    local.run(rsi2.RSI2, feed, parameters_generator())
このコードが実行しているのは3つ

違うパラメーターのジェネレーター関数の宣言
CSVファイルの読み込み
pyalgotrade.optimizer.local モジュールを使って並列実行し最適な結果を求める

ちなみに、ベストな組み合わせを使った時の結果は$1000が$2314.40になった。

  • entrySMA: 154
  • exitSMA: 5
  • rsiPeriod: 2
  • overBoughtThreshold: 91
  • overSoldThreshold: 18


PyAlgoTrade のチュートリアルをかいつまんで訳す その2 トレーディングシミュレーション

PyAlgoTrade慣れてきた気がするので、早速トレーディングしてみる。といってもシミュレーションだけどね。
売買ルールはとても簡単
15日単純移動平均株価を終値が上回ったら買う
15日単純移動平均株価を終値が下回って、株を持っていたら売る
それが以下のプログラムになる


from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.technical import ma


class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument, smaPeriod):
        strategy.BacktestingStrategy.__init__(self, feed, 1000)
        self.__position = None
        self.__instrument = instrument
        # We'll use adjusted close values instead of regular close values.
        self.setUseAdjustedValues(True)
        self.__sma = ma.SMA(feed[instrument].getPriceDataSeries(), smaPeriod)

    def onEnterOk(self, position):
        execInfo = position.getEntryOrder().getExecutionInfo()
        self.info("BUY at $%.2f" % (execInfo.getPrice()))

    def onEnterCanceled(self, position):
        self.__position = None

    def onExitOk(self, position):
        execInfo = position.getExitOrder().getExecutionInfo()
        self.info("SELL at $%.2f" % (execInfo.getPrice()))
        self.__position = None

    def onExitCanceled(self, position):
        # If the exit was canceled, re-submit it.
        self.__position.exitMarket()

    def onBars(self, bars):
        # Wait for enough bars to be available to calculate a SMA.
        if self.__sma[-1] is None:
            return

        bar = bars[self.__instrument]
        # If a position was not opened, check if we should enter a long position.
        if self.__position is None:
            if bar.getPrice() > self.__sma[-1]:
                # Enter a buy market order for 10 shares. The order is good till canceled.
                self.__position = self.enterLong(self.__instrument, 10, True)
        # Check if we have to exit the position.
        elif bar.getPrice() < self.__sma[-1] and not self.__position.exitActive():
            self.__position.exitMarket()


def run_strategy(smaPeriod):
    # Load the yahoo feed from the CSV file
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV("orcl", "orcl-2000.csv")

    # Evaluate the strategy with the feed.
    myStrategy = MyStrategy(feed, "orcl", smaPeriod)
    myStrategy.run()
    print "Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity()

run_strategy(15)

おっと、実行前には株価データの準備を忘れずに
python -c "from pyalgotrade.tools import yahoofinance; yahoofinance.download_daily_bars('orcl', 2000, 'orcl-2000.csv')"
結果は以下のようになる。
2000-01-26 00:00:00 strategy [INFO] BUY at $27.26
2000-01-28 00:00:00 strategy [INFO] SELL at $24.74
2000-02-03 00:00:00 strategy [INFO] BUY at $26.60
2000-02-22 00:00:00 strategy [INFO] SELL at $28.40
2000-02-23 00:00:00 strategy [INFO] BUY at $28.91
2000-03-31 00:00:00 strategy [INFO] SELL at $38.51
2000-04-07 00:00:00 strategy [INFO] BUY at $40.19
2000-04-12 00:00:00 strategy [INFO] SELL at $37.44
2000-04-19 00:00:00 strategy [INFO] BUY at $37.76
2000-04-20 00:00:00 strategy [INFO] SELL at $35.45
2000-04-28 00:00:00 strategy [INFO] BUY at $37.70
2000-05-05 00:00:00 strategy [INFO] SELL at $35.54
2000-05-08 00:00:00 strategy [INFO] BUY at $36.17
2000-05-09 00:00:00 strategy [INFO] SELL at $35.39
2000-05-16 00:00:00 strategy [INFO] BUY at $37.28
2000-05-19 00:00:00 strategy [INFO] SELL at $34.58
2000-05-31 00:00:00 strategy [INFO] BUY at $35.18
2000-06-23 00:00:00 strategy [INFO] SELL at $38.81
2000-06-27 00:00:00 strategy [INFO] BUY at $39.56
2000-06-28 00:00:00 strategy [INFO] SELL at $39.42
2000-06-29 00:00:00 strategy [INFO] BUY at $39.41
2000-06-30 00:00:00 strategy [INFO] SELL at $38.60
2000-07-03 00:00:00 strategy [INFO] BUY at $38.96
2000-07-05 00:00:00 strategy [INFO] SELL at $36.89
2000-07-21 00:00:00 strategy [INFO] BUY at $37.19
2000-07-24 00:00:00 strategy [INFO] SELL at $37.04
2000-07-26 00:00:00 strategy [INFO] BUY at $35.93
2000-07-28 00:00:00 strategy [INFO] SELL at $36.08
2000-08-01 00:00:00 strategy [INFO] BUY at $36.11
2000-08-02 00:00:00 strategy [INFO] SELL at $35.06
2000-08-04 00:00:00 strategy [INFO] BUY at $37.61
2000-09-11 00:00:00 strategy [INFO] SELL at $41.34
2000-09-29 00:00:00 strategy [INFO] BUY at $39.07
2000-10-02 00:00:00 strategy [INFO] SELL at $38.30
2000-10-20 00:00:00 strategy [INFO] BUY at $34.71
2000-10-31 00:00:00 strategy [INFO] SELL at $31.34
2000-11-20 00:00:00 strategy [INFO] BUY at $23.35
2000-11-21 00:00:00 strategy [INFO] SELL at $23.83
2000-12-01 00:00:00 strategy [INFO] BUY at $25.33
2000-12-21 00:00:00 strategy [INFO] SELL at $26.72
2000-12-22 00:00:00 strategy [INFO] BUY at $29.17
Final portfolio value: $979.44

最後のFinal portfolio value: $979.44が最終評価額。ちなみにスタート時は$1000持っている設定だから損をしている。
えー?15日平均がいけなったのかもしれないね。ということで10から30まで順番に試してみよう
run_strategy(15)のところを以下のように書き換える。pythonなのでインデントには注意
for i in range(10, 30):
    run_strategy(i)
これを実行すると以下のような結果になる18日~25日でプラスになる
10 Final portfolio value: $881.22
11 Final portfolio value: $880.92
12 Final portfolio value: $831.48
13 Final portfolio value: $894.46
14 Final portfolio value: $897.38
15 Final portfolio value: $974.33
16 Final portfolio value: $959.99
17 Final portfolio value: $950.26
18 Final portfolio value: $1011.70
19 Final portfolio value: $1041.54
20 Final portfolio value: $1077.24
21 Final portfolio value: $1058.22
22 Final portfolio value: $1060.85
23 Final portfolio value: $1022.82
24 Final portfolio value: $1019.89
25 Final portfolio value: $1013.17
26 Final portfolio value: $998.24
27 Final portfolio value: $982.15
28 Final portfolio value: $975.72
29 Final portfolio value: $983.32

パラメータが1個だと簡単だけど複数だと大変だよね。ということで、その3最適化に続く

2015年8月31日月曜日

PyAlgoTradeのチュートリアルをかいつまんで訳す その1 株価のcsvをもとに移動平均で売買する

チュートリアルから

6つの構成要素について
  • Strategies
    • いつ買っていつ売るかの戦略
  • Feeds
    • 価格データー、例えばカンマ区切りのCSVデータとか
  • Brokers
    • 売買の実行
  • DataSeries
    • 時系列データーの取り扱い
  • Technicals
    • テクニカル指標の計算、移動平均とかRSIとか
  • Optimizer
    • 複数のコンピューターでバックテストを分散処理するためのクラスセット


実際にやってみましょう。
2000年のOracleの株価をyahoo!(米)financeからダウンロードします。


python -c "from pyalgotrade.tools import yahoofinance; yahoofinance.download_daily_bars('orcl', 2000, 'orcl-2000.csv')"

取得したCSVファイルは以下のようになります。
Date,Open,High,Low,Close,Volume,Adj Close
2000-12-29,30.875,31.3125,28.6875,29.0625,31702200,27.208866
2000-12-28,30.5625,31.625,30.375,31.0625,25053600,29.081304
2000-12-27,30.375,31.0625,29.375,30.6875,26437500,28.730222
2000-12-26,31.50,32.1875,30.00,30.9375,20589500,28.964276
2000-12-22,30.375,31.984381,30.00,31.875,35568200,29.841982
2000-12-21,27.8125,30.25,27.3125,29.50,46719700,27.618462
2000-12-20,28.0625,29.8125,27.50,28.50,54440500,26.682243
2000-12-19,31.8125,33.125,30.125,30.625,58653700,28.671708
2000-12-18,30.00,32.4375,29.9375,32.00,61640100,29.959009
2000-12-15,29.4375,30.078119,28.1875,28.5625,120004000,26.740756

OK!  終値を求めるかんたんなストラテジーを書いてみる。
 
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed


class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        strategy.BacktestingStrategy.__init__(self, feed)
        self.__instrument = instrument

    def onBars(self, bars):
        bar = bars[self.__instrument]
        self.info(bar.getClose())

# Load the yahoo feed from the CSV file
feed = yahoofeed.Feed()
feed.addBarsFromCSV("orcl", "orcl-2000.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed, "orcl")
myStrategy.run()
このコードでは3つのことをやってます。

  1.  Strategy(戦略)の宣言、唯一のメソッドonBarsの定義、onBarsはFeedの1行ごとに呼び出されます。 
  2. CSVファイルをFeedに読み込みます。 
  3. Feedに対してStrategyを実行します。
スクリプトを実行すると終値を日付順に確認できます

それじゃあ、単純移動平均を使った売買ルールをストラテジーに書いてみましょう
 
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.technical import ma


class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        strategy.BacktestingStrategy.__init__(self, feed)
        # We want a 15 period SMA over the closing prices.
        self.__sma = ma.SMA(feed[instrument].getCloseDataSeries(), 15)
        self.__instrument = instrument

    def onBars(self, bars):
        bar = bars[self.__instrument]
        self.info("%s %s" % (bar.getClose(), self.__sma[-1]))

# Load the yahoo feed from the CSV file
feed = yahoofeed.Feed()
feed.addBarsFromCSV("orcl", "orcl-2000.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed, "orcl")
myStrategy.run()

変更点は2つ
  • 単純移動平均の初期化を追加
  • 終値の表示に単純移動平均株価を追加

実行すると終値と単純にどう平均を表示するけど、14日目まではNoneになる。15日いどうへいきんだからデーターがないからね。
2000-01-03 00:00:00 strategy [INFO] 118.12 None
2000-01-04 00:00:00 strategy [INFO] 107.69 None
2000-01-05 00:00:00 strategy [INFO] 102.0 None
2000-01-06 00:00:00 strategy [INFO] 96.0 None
2000-01-07 00:00:00 strategy [INFO] 103.37 None
2000-01-10 00:00:00 strategy [INFO] 115.75 None
2000-01-11 00:00:00 strategy [INFO] 112.37 None
2000-01-12 00:00:00 strategy [INFO] 105.62 None
2000-01-13 00:00:00 strategy [INFO] 105.06 None
2000-01-14 00:00:00 strategy [INFO] 106.81 None
2000-01-18 00:00:00 strategy [INFO] 111.25 None
2000-01-19 00:00:00 strategy [INFO] 57.13 None
2000-01-20 00:00:00 strategy [INFO] 59.25 None
2000-01-21 00:00:00 strategy [INFO] 59.69 None
2000-01-24 00:00:00 strategy [INFO] 54.19 94.2866666667
2000-01-25 00:00:00 strategy [INFO] 56.44 90.1746666667
.
.
.
2000-12-27 00:00:00 strategy [INFO] 30.69 29.9866666667
2000-12-28 00:00:00 strategy [INFO] 31.06 30.0446666667

その他すべての指標は計算できないときはNullになる。
連続したデータに対して使うように設計されているため、複数の指標を組み合わせて使うことができる。
例えば、単純移動平均とRSAとか

from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.technical import ma
from pyalgotrade.technical import rsi


class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        strategy.BacktestingStrategy.__init__(self, feed)
        self.__rsi = rsi.RSI(feed[instrument].getCloseDataSeries(), 14)
        self.__sma = ma.SMA(self.__rsi, 15)
        self.__instrument = instrument

    def onBars(self, bars):
        bar = bars[self.__instrument]
        self.info("%s %s %s" % (bar.getClose(), self.__rsi[-1], self.__sma[-1]))

# Load the yahoo feed from the CSV file
feed = yahoofeed.Feed()
feed.addBarsFromCSV("orcl", "orcl-2000.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed, "orcl")
myStrategy.run()
実行結果はこうなる
最初の14日RSIはNoneになる
最初の28日間移動平均はNoneになる。なぜなら14日後のRSIの平均をとるためにはさらに15日必要だからね。
2000-01-03 00:00:00 strategy [INFO] 118.12 None None
2000-01-04 00:00:00 strategy [INFO] 107.69 None None
2000-01-05 00:00:00 strategy [INFO] 102.0 None None
2000-01-06 00:00:00 strategy [INFO] 96.0 None None
2000-01-07 00:00:00 strategy [INFO] 103.37 None None
2000-01-10 00:00:00 strategy [INFO] 115.75 None None
2000-01-11 00:00:00 strategy [INFO] 112.37 None None
2000-01-12 00:00:00 strategy [INFO] 105.62 None None
2000-01-13 00:00:00 strategy [INFO] 105.06 None None
2000-01-14 00:00:00 strategy [INFO] 106.81 None None
2000-01-18 00:00:00 strategy [INFO] 111.25 None None
2000-01-19 00:00:00 strategy [INFO] 57.13 None None
2000-01-20 00:00:00 strategy [INFO] 59.25 None None
2000-01-21 00:00:00 strategy [INFO] 59.69 None None
2000-01-24 00:00:00 strategy [INFO] 54.19 23.5673530141 None
2000-01-25 00:00:00 strategy [INFO] 56.44 25.0687519877 None
2000-01-26 00:00:00 strategy [INFO] 55.06 24.7476577095 None
2000-01-27 00:00:00 strategy [INFO] 51.81 23.9690136517 None
2000-01-28 00:00:00 strategy [INFO] 47.38 22.9108539956 None
2000-01-31 00:00:00 strategy [INFO] 49.95 24.980004823 None
2000-02-01 00:00:00 strategy [INFO] 54.0 28.2484181864 None
2000-02-02 00:00:00 strategy [INFO] 54.31 28.505177315 None
2000-02-03 00:00:00 strategy [INFO] 56.69 30.5596770599 None
2000-02-04 00:00:00 strategy [INFO] 57.81 31.5564353751 None
2000-02-07 00:00:00 strategy [INFO] 59.94 33.5111056589 None
2000-02-08 00:00:00 strategy [INFO] 59.56 33.3282358994 None
2000-02-09 00:00:00 strategy [INFO] 59.94 33.7177605915 None
2000-02-10 00:00:00 strategy [INFO] 62.31 36.2205441255 None
2000-02-11 00:00:00 strategy [INFO] 59.69 34.6623493641 29.0368892505
2000-02-14 00:00:00 strategy [INFO] 62.19 37.4284445543 29.9609620198
.
.
.
2000-12-27 00:00:00 strategy [INFO] 30.69 51.3196802735 49.8506368511
2000-12-28 00:00:00 strategy [INFO] 31.06 52.1646203455 49.997518354
2000-12-29 00:00:00 strategy [INFO] 29.06 47.3776678335 50.0790646925

2015年8月30日日曜日

PyAlgoTradeが出力するグラフの出力先を変更したい

Strategy plotter という便利なライブラリがあって結果を画像で出力してくれるがX11環境が必要。
たぶん、慣れてしまえばチャートは不要だと思うけど最初は確認したい。
ライブラリの中で出力先は固定されているので、画像ファイルに出力するにはライブラリ自体の書き換える。たぶん、アップデートごとに動かなくなるので、本体が対応してくれたらいいんだけど。

修正作業手順

/usr/lib64/python2.7/site-packages/pyalgotrade/plotter.py の最後にあるplot関数を書き換える

オリジナル
    def plot(self, fromDateTime=None, toDateTime=None):
        """Plots the strategy execution. Must be called after running the strategy.

        :param fromDateTime: An optional starting datetime.datetime. Everything before it won't get plotted.
        :type fromDateTime: datetime.datetime
        :param toDateTime: An optional ending datetime.datetime. Everything after it won't get plotted.
        :type toDateTime: datetime.datetime
        """

        fig, mplSubplots = self.__buildFigureImpl(fromDateTime, toDateTime)
        fig.autofmt_xdate()
        plt.show()

修正後
    def plot(self, fromDateTime=None, toDateTime=None,fileName=""):
        """Plots the strategy execution. Must be called after running the strategy.

        :param fromDateTime: An optional starting datetime.datetime. Everything before it won't get plotted.
        :type fromDateTime: datetime.datetime
        :param toDateTime: An optional ending datetime.datetime. Everything after it won't get plotted.
        :type toDateTime: datetime.datetime
        """

        fig, mplSubplots = self.__buildFigureImpl(fromDateTime, toDateTime)
        fig.autofmt_xdate()
        if(len(fileName)):
            plt.savefig(fileName)
        else:
            plt.show()
もちろん、メインプログラムにはAggを指定するのはお約束
import matplotlib
matplotlib.use('Agg')


追記

 buildFigureを使えばfigオブジェクトを返してくれるので、あとは保存するなり煮るなり焼くなりすればいいことに気が付いた。
つまり、改造は不要で以下のように使えばいい。これでアップデートも怖くない

fig=plt.buildFigure(None,None)
fig.savefig("myoutput.png")

PyAlogTradeに決めた

アルゴリズムトレードライブラリを使ってみる。

参考にしたQiitaの記事

Ziplineは参考にできる記事が多いので、天邪鬼にPyAlogTradeとしばらく付き合ってみようと思う


ちなみに、ほかに紹介されているultrafinanceはpipでインストールができなかった。
QSTKはpipでインストール中にエラーが出て先に進まない、ubuntuだったらうまくいくかも。