PyAlgoTradeの日本語解説ブログ

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

2015年9月30日水曜日

PyAlgoTrade グラフを保存するためのもっとスマートな方法

 今まで、linuxコンソール以外で実行するためにplotter.pyを改造してきたが、その必要がないことがplotter.pyのソースを読んでいて分かった。
 呼び出すほうを工夫すれば無改造でかまわない。

今まで

オリジナルでは
plt.plot(None,None)
改造したライブラリでは
plt.plot(None,None,"output.png")


としていたところを、以下の2行でいい

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

いい加減な情報を提供して申し訳ない。

2015年9月23日水曜日

PyAlgoTrade を使える仲間を探している

投資は自分との闘いとはいえ、一人で黙々とやっているのはうんざりしますよね。
PyAlgoTradeに関するつながりを求めて検索してみました。


Google Groups

PyAlgoTrade
https://groups.google.com/forum/#!forum/pyalgotrade

twitter
全然活発ではない
https://twitter.com/pyalgotrade

freelancer
お金を払えばpythonのプログラムを作ってくれます。
https://www.freelancer.com.au/job-search/pyalgotrade/1/

英語ばかりです。


PyAlgoTrade データ取得方法を見直して任意のデータを扱えるようにする

以前に米Yahoo!に頼らない方法としてjsmを使って日本のYahoo!から取得する方法を紹介した。


日本の時系列株価データーがほしい時にはjsmを使う
http://pyalgotradejp.blogspot.jp/2015/09/jsm.html

手元に蓄積したデータがあってそれを使いたい場合は、feedにCSVファイルを読み込むことができる。

まずはフィードにCSVから読み込む改造
9997は証券コードだが、別に何でもいい。test.csvからデータをフィードに取り込んでいる。

ポイントは3つ from pyalgotrade.barfeed import csvfeed
feed = csvfeed.GenericBarFeed(bar.Frequency.DAY)
feed.addBarsFromCSV("9997","test.csv")
あとはいつもと変わらない。
#!/usr/bin/python
# -*- coding: utf-8 -*-
import matplotlib 
matplotlib.use('Agg')
from pyalgotrade import plotter
from pyalgotrade.technical import highlow
from pyalgotrade import strategy
from pyalgotrade import bar
from pyalgotrade.barfeed import csvfeed
from pyalgotrade.technical import cross


class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        strategy.BacktestingStrategy.__init__(self, feed)
        self.__prices = feed[instrument].getPriceDataSeries()
        self.__high = highlow.High(feed[instrument].getCloseDataSeries(),10)
        self.__low = highlow.Low(feed[instrument].getCloseDataSeries(),10)
        self.__instrument = instrument

    def onBars(self, bars):
        bar = bars[self.__instrument]
        self.info("%f Hi:%s Lo:%s" % (self.__prices[-1],self.__high[-1],self.__low[-1]))


# Load the Local feed from the CSV file
feed = csvfeed.GenericBarFeed(bar.Frequency.DAY)
feed.addBarsFromCSV("9997","test.csv")

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

plt = plotter.StrategyPlotter(myStrategy, True, True, True)
myStrategy.run()
plt.plot(None,None,"output.png")



データベースから直接読み取りたいところであるが、サポートしていないようだ。
仕方ないので、データベースからcsvで書き出すプログラムを書いた。「それSQLでできるよ」なのだが、指定のヘッダーが必ず必要なのでどうせならとpythonで書いてしまった。


#/usr/bin/python

import MySQLdb
from MySQLdb.cursors import DictCursor

import sys

argvs = sys.argv
argc = len(argvs)
if(argc != 2):
 print "usage: # python %s code" % argvs[0]
 quit()
code=argvs[1]

connection = MySQLdb.connect(db="stock",user="stock")

cursor = connection.cursor()

cursor.execute("select * from bulk_data where code=%s order by reg_date",(code,))
result=cursor.fetchall()

print "Date Time,Open,High,Low,Close,Volume"
for row in result:
 print("%s 15:00:00,%d,%d,%d,%d,%d" % (row[0],row[2],row[3],row[4],row[5],row[6]))

cursor.close()
connection.close()

ぶっちゃけシェルスクリプトで書くこともできるが、あえてpythonで書く。というのも、調整終値の欄がないからだ。
 分割などでいきなり株価が半分になっているのを権利落ち修正しないとデーターの連続性がなくなってしまう。データーがないのであればいっそ切り捨てたほうがいい。というような処理をしたいときに困るだろうという配慮だ。
 ちなみに、この銘柄は2014年1月に分割している


PyAlgoTrade の plot機能でグラフを書く

今までガン無視してきたplotについて、まとめて取り上げます。

グラフを書くにはplt クラスを定義して、strategyをrunした後にplotします。
stategyを実行した後にまとめてグラフ関係を処理したいのですが、必ず間に挟まないとダメみたいです。その割にはOnBarsで計算した値を先に指定するとか、よくよく考えれば順番がおかしい気がしますが、動いているからいいのです。

この間のvwapを使ったサンプルを改造してテストします。
出力するグラフは4枚、

まず
plotter.StrategyPlotter(strat, arg1, arg2, arg3)

arg1 値動きと取引に関するグラフのON/OFF
arg2 Buy-Sellマークを付ける
arg3 ポートフォリオのグラフのON/OFF

ある程度を組み合わせたものを下のプログラムに書きました。


import matplotlib 
matplotlib.use('Agg')
from pyalgotrade import strategy
from pyalgotrade import plotter
from pyalgotrade.tools import yahoofinance
from pyalgotrade.technical import vwap
from pyalgotrade.stratanalyzer import sharpe
import numpy as np

class VWAPMomentum(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument, vwapWindowSize, threshold):
        strategy.BacktestingStrategy.__init__(self, feed)
        self.__instrument = instrument
        self.__vwap = vwap.VWAP(feed[instrument], vwapWindowSize)
        self.__threshold = threshold
        self.__price= feed[instrument].getPriceDataSeries()
        self.__delta= []
        self.__notional=[]

    def getVWAP(self):
        return self.__vwap

    def getDelta(self):
        return self.__delta

    def getNotional(self):
        return self.__notional

    def onBars(self, bars):
        vwap = self.__vwap[-1]
        if vwap is None:
            return
        price = self.__price[-1]
        shares = self.getBroker().getShares(self.__instrument)
        #price = bars[self.__instrument].getClose()
        notional = shares * price
        self.__delta.append(price-vwap)
        self.__notional.append(notional)
        if price > vwap * (1 + self.__threshold) and notional < 1000000:
            self.marketOrder(self.__instrument, 100)
        elif price < vwap * (1 - self.__threshold) and notional > 0:
            self.marketOrder(self.__instrument, -100)


def main():
    instrument = "aapl"
    vwapWindowSize = 25
    threshold = 0.01

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

    strat = VWAPMomentum(feed, instrument, vwapWindowSize, threshold)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    plt = plotter.StrategyPlotter(strat, True, True, True) #standard use
    plt.getInstrumentSubplot(instrument).addDataSeries("vwap", strat.getVWAP()) #Add VWAP Line

    plt2 = plotter.StrategyPlotter(strat, True, True, False) # without portfolio
    plt3 = plotter.StrategyPlotter(strat, False, True, True) #portfolio only

    plt4 = plotter.StrategyPlotter(strat, True, True, False) #Optional Graph
    plt4.getOrCreateSubplot("delta").addDataSeries("price-vwap", strat.getDelta())
    plt4.getOrCreateSubplot("notional").addDataSeries("notional", strat.getNotional())
    plt4.getOrCreateSubplot("notional").addLine("limit", 1000000)
    
    strat.run()
 
    plt.plot(None,None,"output.png")
    plt2.plot(None,None,"output2.png")
    plt3.plot(None,None,"output3.png")
    plt4.plot(None,None,"output4.png")

if __name__ == "__main__":
    main()


出力されるのは以下のグラフです。
output.png

output2.png

output3.png

output4.png
出力サイズは決まっているみたいなので、拡大したければ不要なグラフを削るしかなさそうです。
4番目のグラフは指標ではなくデバッグで作ってみました。
価格とVWAPを引いた値、価格と出来高をかけたnotionalの値をプロットして、意図したタイミングで売買がされているかを確認するためのものです。

2015年9月22日火曜日

PyAlgoTrade サンプルの動作を調べる RSI2を使った売買

 RSI2という戦略があるらしい。

http://stockcharts.com/school/doku.php?id=chart_school:trading_strategies:rsi2

 ざっくり説明を読んだところ、200日移動平均のような長いスパンの線に対して、長期の上昇を続けているまたはその逆に下がり続けているような場合に押し目を待って市場に参入する作戦だ。押し目の判定はRSIを使う
 「押し目待ちに押し目なし」という格言に逆らっているようだ。
 ストップロスをセットしておかないと押し目ではなく本当にブレイクしてしまうことがあるので注意。


サンプルとして掲載されていたオリジナルは2ファイルに分かれていたけど、一つにした。
でもって、ストップロスを入れていない無謀な取引


import matplotlib 
matplotlib.use('Agg')
from pyalgotrade import strategy
from pyalgotrade.technical import ma
from pyalgotrade.technical import rsi
from pyalgotrade.technical import cross
from pyalgotrade import plotter
from pyalgotrade.tools import yahoofinance
from pyalgotrade.stratanalyzer import sharpe


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



def main(plot):
    instrument = "DIA"
    entrySMA = 200
    exitSMA = 5
    rsiPeriod = 2
    overBoughtThreshold = 90
    overSoldThreshold = 10

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

    strat = RSI2(feed, instrument, entrySMA, exitSMA, rsiPeriod, overBoughtThreshold, overSoldThreshold)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, True, True)
        plt.getInstrumentSubplot(instrument).addDataSeries("Entry SMA", strat.getEntrySMA())
        plt.getInstrumentSubplot(instrument).addDataSeries("Exit SMA", strat.getExitSMA())
        plt.getOrCreateSubplot("rsi").addDataSeries("RSI", strat.getRSI())
        plt.getOrCreateSubplot("rsi").addLine("Overbought", overBoughtThreshold)
        plt.getOrCreateSubplot("rsi").addLine("Oversold", overSoldThreshold)

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

    if plot:
        plt.plot(None,None,"output.png")


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


結果は以下の通り。
シャープレシオは-0.68です。残念。
でも、これは実装に問題があるような気がする。移動平均と株価がクロスするような場所で使ってはいけない戦略なのに単純に平均線の上か下しか見ていないから。
 案の定クロス付近で財産を失う。




StockChartsは様々な戦略を紹介している。RSI2はこの中の戦略の一つ。


StockCharts.com - Articles
Trading Strategies and Models
http://stockcharts.com/school/doku.php?id=chart_school:trading_strategies

PyAlgoTrade サンプルの動作を調べる ボリンジャーバンドを使った売買

また、シンプルな売買プログラムに戻ります。
移動平均をボリンジャーバンドに置き換えただけの簡単なプログラムです。
2σの線にタッチしたら売りまたは買いを行います。

ボリンジャーバンドの期間は40日対象は米Yahooとmainの最初で定義しています。

import matplotlib 
matplotlib.use('Agg')
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(None,None,"output.png")


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


実行すると現金不足のエラーが出ます。残金を確認せずに発注しているので仕方ないです。


シャープレシオは0.71をたたき出しました。いいですね。
売りと買いを同時に行っているので往復で稼いでいます。


SellとBuyにわかりやすくマークがついています。これを出すのはStrategyPlotterの3番目の引数をTrueにします。
よく見ると買った瞬間から下がってしまい、売った直後から上がってます。頭としっぽはくれてやれといいますが、ほとんど食われているような。

PyAlgoTrade サンプルの動作を調べる マーケットタイミングと移動平均のクロスを使った売買

今回はぐっと難易度が上がります。市況のデーターを合わせて判断します。


import matplotlib 
matplotlib.use('Agg')
from pyalgotrade import strategy
from pyalgotrade import plotter
from pyalgotrade.tools import yahoofinance
from pyalgotrade.technical import ma
from pyalgotrade.technical import cumret
from pyalgotrade.stratanalyzer import sharpe
from pyalgotrade.stratanalyzer import returns


class MarketTiming(strategy.BacktestingStrategy):
    def __init__(self, feed, instrumentsByClass, initialCash):
        strategy.BacktestingStrategy.__init__(self, feed, initialCash)
        self.setUseAdjustedValues(True)
        self.__instrumentsByClass = instrumentsByClass
        self.__rebalanceMonth = None
        self.__sharesToBuy = {}
        # Initialize indicators for each instrument.
        self.__sma = {}
        for assetClass in instrumentsByClass:
            for instrument in instrumentsByClass[assetClass]:
                priceDS = feed[instrument].getPriceDataSeries()
                self.__sma[instrument] = ma.SMA(priceDS, 200)

    def _shouldRebalance(self, dateTime):
        return dateTime.month != self.__rebalanceMonth

    def _getRank(self, instrument):
        # If the price is below the SMA, then this instrument doesn't rank at
        # all.
        smas = self.__sma[instrument]
        price = self.getLastPrice(instrument)
        if len(smas) == 0 or smas[-1] is None or price < smas[-1]:
            return None

        # Rank based on 20 day returns.
        ret = None
        lookBack = 20
        priceDS = self.getFeed()[instrument].getPriceDataSeries()
        if len(priceDS) >= lookBack and smas[-1] is not None and smas[-1*lookBack] is not None:
            ret = (priceDS[-1] - priceDS[-1*lookBack]) / float(priceDS[-1*lookBack])
        return ret

    def _getTopByClass(self, assetClass):
        # Find the instrument with the highest rank.
        ret = None
        highestRank = None
        for instrument in self.__instrumentsByClass[assetClass]:
            rank = self._getRank(instrument)
            if rank is not None and (highestRank is None or rank > highestRank):
                highestRank = rank
                ret = instrument
        return ret

    def _getTop(self):
        ret = {}
        for assetClass in self.__instrumentsByClass:
            ret[assetClass] = self._getTopByClass(assetClass)
        return ret

    def _placePendingOrders(self):
        remainingCash = self.getBroker().getCash() * 0.9  # Use less chash just in case price changes too much.

        for instrument in self.__sharesToBuy:
            orderSize = self.__sharesToBuy[instrument]
            if orderSize > 0:
                # Adjust the order size based on available cash.
                lastPrice = self.getLastPrice(instrument)
                cost = orderSize * lastPrice
                while cost > remainingCash and orderSize > 0:
                    orderSize -= 1
                    cost = orderSize * lastPrice
                if orderSize > 0:
                    remainingCash -= cost
                    assert(remainingCash >= 0)

            if orderSize != 0:
                self.info("Placing market order for %d %s shares" % (orderSize, instrument))
                self.marketOrder(instrument, orderSize, goodTillCanceled=True)
                self.__sharesToBuy[instrument] -= orderSize

    def _logPosSize(self):
        totalEquity = self.getBroker().getEquity()
        positions = self.getBroker().getPositions()
        for instrument in self.getBroker().getPositions():
            posSize = positions[instrument] * self.getLastPrice(instrument) / totalEquity * 100
            self.info("%s - %0.2f %%" % (instrument, posSize))

    def _rebalance(self):
        self.info("Rebalancing")

        # Cancel all active/pending orders.
        for order in self.getBroker().getActiveOrders():
            self.getBroker().cancelOrder(order)

        cashPerAssetClass = self.getBroker().getEquity() / float(len(self.__instrumentsByClass))
        self.__sharesToBuy = {}

        # Calculate which positions should be open during the next period.
        topByClass = self._getTop()
        for assetClass in topByClass:
            instrument = topByClass[assetClass]
            self.info("Best for class %s: %s" % (assetClass, instrument))
            if instrument is not None:
                lastPrice = self.getLastPrice(instrument)
                cashForInstrument = cashPerAssetClass - self.getBroker().getShares(instrument) * lastPrice
                # This may yield a negative value and we have to reduce this
                # position.
                self.__sharesToBuy[instrument] = int(cashForInstrument / lastPrice)

        # Calculate which positions should be closed.
        for instrument in self.getBroker().getPositions():
            if instrument not in topByClass.values():
                currentShares = self.getBroker().getShares(instrument)
                assert(instrument not in self.__sharesToBuy)
                self.__sharesToBuy[instrument] = currentShares * -1

    def getSMA(self, instrument):
        return self.__sma[instrument]

    def onBars(self, bars):
        currentDateTime = bars.getDateTime()

        if self._shouldRebalance(currentDateTime):
            self.__rebalanceMonth = currentDateTime.month
            self._rebalance()

        self._placePendingOrders()


def main(plot):
    initialCash = 10000
    instrumentsByClass = {
        "US Stocks": ["VTI"],
        "Foreign Stocks": ["VEU"],
        "US 10 Year Government Bonds": ["IEF"],
        "Real Estate": ["VNQ"],
        "Commodities": ["DBC"],
    }

    # Download the bars.
    instruments = ["SPY"]
    for assetClass in instrumentsByClass:
        instruments.extend(instrumentsByClass[assetClass])
    feed = yahoofinance.build_feed(instruments, 2007, 2013, "data", skipErrors=True)

    strat = MarketTiming(feed, instrumentsByClass, initialCash)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)
    returnsAnalyzer = returns.Returns()
    strat.attachAnalyzer(returnsAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, False, False, True)
        plt.getOrCreateSubplot("cash").addCallback("Cash", lambda x: strat.getBroker().getCash())
        # Plot strategy vs. SPY cumulative returns.
        plt.getOrCreateSubplot("returns").addDataSeries("SPY", cumret.CumulativeReturn(feed["SPY"].getPriceDataSeries()))
        plt.getOrCreateSubplot("returns").addDataSeries("Strategy", returnsAnalyzer.getCumulativeReturns())

    strat.run()
    print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)
    print "Returns: %.2f %%" % (returnsAnalyzer.getCumulativeReturns()[-1] * 100)

    if plot:
        plt.plot(None,None,"output.png")


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


いやー、深く考えれば考えるほど泥沼なんでしょうか。ついにシャープレシオはマイナスになりました。