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

ziplineのインストールで躓いて、「環境問題めんどくせーなー。とりあえず躓かないライブラリにしよう。」なんてことを思っている軟弱者です。
Pythonのバックテストフレームワーク「zipline」を使ってみる1 〜 環境構築」で辛うじてziplineを導入出来たかのように思えたが、エラーが発生して、原因はエラーメッセージ通りなので1つずつ解決していけば解決出来ると思うが、面倒ということで「PyAlgoTrade」を先に使ってみることに方針変更w。

pycharmのライブラリで検索すると発見。
この段階でのバージョンは0.18。

容易にインストールに成功。
※)ziplineのインストールには「Windows Scipy Install: No Lapack/Blas Resources Found」というエラーにも遭遇して萎えたが、PyAlgoTradeは成功。lapack使っていなのだろう。

とりあえず、色々楽をするためにサンプルコードはQiitaの記事「pythonのアルゴリズムトレードライブラリ」から引用。

下記はQiitaの記事「pythonのアルゴリズムトレードライブラリ」からのコピペです。

from pyalgotrade import strategy
from pyalgotrade import plotter
from pyalgotrade.tools import yahoofinance
from pyalgotrade.technical import bollinger
from pyalgotrade.stratanalyzer import sharpe


class BBands(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument, bBandsPeriod):
        strategy.BacktestingStrategy.__init__(self, feed)
        self.__instrument = instrument
        self.__bbands = bollinger.BollingerBands(feed[instrument].getCloseDataSeries(), bBandsPeriod, 2)

    def getBollingerBands(self):
        return self.__bbands

    def onBars(self, bars):
        lower = self.__bbands.getLowerBand()[-1]
        upper = self.__bbands.getUpperBand()[-1]
        if lower is None:
            return

        shares = self.getBroker().getShares(self.__instrument)
        bar = bars[self.__instrument]
        if shares == 0 and bar.getClose() < lower:
            sharesToBuy = int(self.getBroker().getCash(False) / bar.getClose())
            self.marketOrder(self.__instrument, sharesToBuy)
        elif shares > 0 and bar.getClose() > upper:
            self.marketOrder(self.__instrument, -1*shares)


def main(plot):
    instrument = "yhoo"
    bBandsPeriod = 40

    # Download the bars.
    feed = yahoofinance.build_feed([instrument], 2011, 2012, ".")

    strat = BBands(feed, instrument, bBandsPeriod)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, True, True)
        plt.getInstrumentSubplot(instrument).addDataSeries("upper", strat.getBollingerBands().getUpperBand())
        plt.getInstrumentSubplot(instrument).addDataSeries("middle", strat.getBollingerBands().getMiddleBand())
        plt.getInstrumentSubplot(instrument).addDataSeries("lower", strat.getBollingerBands().getLowerBand())

    strat.run()
    print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)

    if plot:
        plt.plot()


if __name__ == "__main__":
    main(True)

実行してみると、動いた。
今は環境構築で躓きたくないので、とりあえずPyAlgoTradeを使おう。twitter連携のサンプルもあるし。