PyAlgoTradeの日本語解説ブログ

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

2015年9月21日月曜日

PyalgTrade で ボリンジャーバンド(BollingerBands)を使う

非常に使っている人が多いボリンジャーバンドについて触れないわけにはいくまい。いや、その他ATRとかCumulativeReturnとかは何を言っているのかわからないのでパス。わかったら書きます。

ボリンジャーバンドは中心を移動平均線、その上と下にσの線を引きます。2σの線を超えることは95%ないということらしいのですが、これで大やけどをする人もいいるそうなので使い方には注意が必要です。

さて、ボリンジャーバンドを使うプログラムは以下のようになります。σ=2を指定してます。



#!/usr/bin/python
# -*- coding: utf-8 -*-
import logging
from pyalgotrade.technical import bollinger
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed

logging.basicConfig(filename='/tmp/exec.log')

class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        strategy.BacktestingStrategy.__init__(self, feed)
        sigma=2
        self.__bband = bollinger.BollingerBands(feed[instrument].getCloseDataSeries(),15, sigma)
        self.__bbandLow = self.__bband.getLowerBand()
        self.__bbandMiddle = self.__bband.getMiddleBand()
        self.__bbandUpper = self.__bband.getUpperBand()
        self.__instrument = instrument

    def onBars(self, bars):
        bar = bars[self.__instrument]
        self.info("%f Low:%s Middle:%s Upper:%s" % (bar.getClose(),self.__bbandLow[-1],self.__bbandMiddle[-1],self.__bbandUpper[-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()
解説は各動画で

kabu.comの解説
 ボリンジャーバンド

PyAlgoTrade MACD RSI StochasticOscillator RateOfChange モメンタム指標を使う



モメンタム(慣性)ってなんだっけ

モメンタム投資とは、現在の株価のトレンドが継続することを想定した投資ストラテジーです

15分でわかるモメンタム投資より

 ということで、昨日まで上がっていたものは上がるし下がっていたものは下がる。毎日変わるような相場は休め。という戦略らしい。

PyAlgoTradeで使えるモメンタムに関する指標は以下の通り

  • MACD
  • RSI
  • StochasticOscillator
  • RateOfChange

早速プログラムで使ってみる。まずはMACD

#!/usr/bin/python
# -*- coding: utf-8 -*-
import logging
from pyalgotrade.technical import macd
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed

logging.basicConfig(filename='/tmp/exec.log')

class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        strategy.BacktestingStrategy.__init__(self, feed)
        firstEMA=12
        slowEMA=26
        signalEMA=9
        self.__macd = macd.MACD(feed[instrument].getCloseDataSeries(),firstEMA, slowEMA, signalEMA)
        self.__macdHistgram=self.__macd.getHistogram()
        self.__macdSignal=self.__macd.getSignal()
        self.__instrument = instrument

    def onBars(self, bars):
        bar = bars[self.__instrument]
        self.info("%f MACD:%s Histgram:%s Signal:%s " % (bar.getClose(),self.__macd[-1],self.__macdHistgram[-1],self.__macdSignal[-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()

MACDの3つの追加パラメーターについて補足説明。 長期の移動平均と短期の移動平均の差を求めて計算するためそれぞれ指定する、またMACDの移動平均となるシグナル線の期間も指定する。標準は26,12,9が使われる。別のソフトだけど以下の動画の説明が詳しい。


次はRSI、買われすぎや売られすぎの指標として補助的に移動平均と一緒に使われることがあ多いが、ライブラリもまた移動平均と同様にデータ列と期間を与えることで使用することができる。

#!/usr/bin/python
# -*- coding: utf-8 -*-
import logging
from pyalgotrade.technical import rsi
from pyalgotrade.technical import ma
from pyalgotrade.technical import vwap
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed

logging.basicConfig(filename='/tmp/exec.log')

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

    def onBars(self, bars):
        bar = bars[self.__instrument]
        self.info("%f RSI:%s " % (bar.getClose(),self.__rsi[-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()



こちらもMACD同様に動画の説明が詳しい
Stochastic oscillator (ストキャスティクス)と ROCもRSI同様に計算できる。
#!/usr/bin/python
# -*- coding: utf-8 -*-
import logging
from pyalgotrade.technical import rsi
from pyalgotrade.technical import stoch
from pyalgotrade.technical import roc
from pyalgotrade.technical import ma
from pyalgotrade.technical import vwap
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed

logging.basicConfig(filename='/tmp/exec.log')

class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        strategy.BacktestingStrategy.__init__(self, feed)
        self.__rsi = rsi.RSI(feed[instrument].getCloseDataSeries(), 15)
        self.__so = stoch.StochasticOscillator(feed[instrument], 15)
        self.__roc =roc.RateOfChange(feed[instrument].getCloseDataSeries(), 15)
        self.__instrument = instrument

    def onBars(self, bars):
        bar = bars[self.__instrument]
        self.info("%f RSI:%s StochasticOscillator:%s RateOfChange:%s " % (bar.getClose(),self.__rsi[-1],self.__so[-1],self.__roc[-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()

動画の説明はわかりやすくていいな。でもROCの説明動画は見つかりませんでした





文章での説明は、証券会社各社で提供されているがカブドッドコム証券のテクニカル分析ABCがわかりやすかった。
 テクニカル分析ABC http://kabu.com/investment/guide/technical/default.html


2015年9月20日日曜日

PyAlgoTradeで使える移動平均いろいろ

仕様を調べていたら、売買まで進みません。まあ、間違った使い方で無駄に一喜一憂するよりはマシ、マーケットは明日もあいている。ということで、


移動平均については以下の4つをサポートしているが、SMAとEMA以外は呼び出し方が違う。



  • SMA(Simple Moving Average)・・・単純移動平均線
  • EMA(Exponential Moving Average)・・・指数移動平均線
  • WMA(Weighted Moving Average)・・・加重移動平均線
  • VWAP (Volume Weighted Average Price) 出来高加重移動平均

SMA->EMA->WMAの順に直近の価格が優先される。このソフトの場合のWMAは比率を自分で決めることができる。
たとえば、昨日:一昨日を3:1で平均を取ったのが以下のサンプル。とはいえほぼ昨日の株価になってしまうので、10日分ぐらいはブレンドするよね。

VMAPは所属しているライブラリが違う。また、引数としては株価データを全部渡す。計算には価格と出来高が必要だから。ちなみに読み方は「ブイワップ」でかっこいい。
株価がVWAPを上回っている時は、今日買った人全員の損益を合計したらプラス、逆に株価がVWAPを下回っている場合はマイナスになる。

それでは、全部計算してみましょう


#!/usr/bin/python
# -*- coding: utf-8 -*-
import logging
from pyalgotrade.technical import ma
from pyalgotrade.technical import vwap
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed

logging.basicConfig(filename='/tmp/exec.log')

class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        strategy.BacktestingStrategy.__init__(self, feed)
 self.__sma = ma.SMA(feed[instrument].getCloseDataSeries(), 15)
 self.__ema = ma.EMA(feed[instrument].getCloseDataSeries(), 15)
 self.__wma = ma.WMA(feed[instrument].getCloseDataSeries(), (1,2))
 self.__vwap =vwap.VWAP(feed[instrument], 15)
        self.__instrument = instrument

    def onBars(self, bars):
        bar = bars[self.__instrument]
        self.info("%f sma:%s ema:%s wma:%s vwap:%s " % (bar.getClose(),self.__sma[-1],self.__ema[-1],self.__wma[-1],self.__vwap[-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()

次はRSIなどのモメンタムかな。

2015年9月16日水曜日

PyAlgoTrade 今までのおさらい

「よーし、OKだなんでも書けるぞ」と思ったら1行もかけない罠 そこで復讐いや復習です。
 基本のプログラムを最小限のものに絞り込みます。
class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
       pass
    def onBars(self, bars):
       pass

feed = yahoofeed.Feed()
myStrategy = MyStrategy(feed, "orcl")
myStrategy.run()



つまり、  プログラム MyStrategyクラスを定義 onBarsを書く 株価をfeedとして取得し feedを引数にしてMyStrategyのクラスを作成 それをrun() 実行結果 feedのすべてのレコード一つ一つに対してMyStrategyのonBarsが呼び出される 唯一の引数はbars、feedで与えられた価格のほかに各種指標の当日分が入っている。

 onBarsの中ではprint関数を使うこともできるが、self.info()関数を使うと、日時をつけて表示してくれる。info 同様に debug,warning,error,criticalなどが用意されているので適宜使い分ける。
import logging で logging.basicConfigを設定するとファイルやシステムログに記録することができる。

 onBars関数の中では、1日分のデーターが取得できる。各値はメソッド関数を呼び出して使用する

  • bar.getOpen()  始値
  • bar.getHigh() 高値
  • bar.getLow() 安値
  • bar.getClose() 終値
  • bar.getAdjClose() 調整終値
  • bar.getPrice() 終値か調整終値のどちらか
これらを表示させると以下のようなプログラムになる。


#!/usr/bin/python
# -*- coding: utf-8 -*-
import logging
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed

logging.basicConfig(filename='/tmp/exec.log')

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("%f %f %f %f %f %d" % (bar.getOpen(),bar.getHigh(),bar.getLow(),bar.getClose(),bar.getAdjClose(),bar.getVolume()))


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

当日分のデータだけだと、値段と取引量の絶対値と陽線か陰線かしかわからない。
移動平均とか以前のデータから計算する指標は最初に計算してやはりOnBars関数の中で参照する。
例えば15日移動平均を参照するには

  • from pyalgotrade.technical import ma でライブラリをインポート
  • 初期化__init__の中に self.__sma = ma.SMA(feed[instrument].getCloseDataSeries(), 15) で15日移動平均を計算してしまう。
  • onBarsでは self.__sma[-1]で参照する。忘れがちなので注意

また移動平均は終値を指定して計算させているが、、毎日とれているデータであればなんでもいい。

終値と移動平均を表示させてみる


#!/usr/bin/python
# -*- coding: utf-8 -*-
import logging
from pyalgotrade.technical import ma
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed

logging.basicConfig(filename='/tmp/exec.log')

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

    def onBars(self, bars):
        bar = bars[self.__instrument]
        self.info("%f %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()
おわかりだろうか、self.infoのフォーマットが %fから%sに変わっている。
なぜかというと計算できないときはnoneになるので実数として表示できないからだ。
この後は指標をいろいろ試してみようかな。

Quantopian が理想的なシステムトレーディングのテスト場かもしれない

折角PyAlgoTradeをインストールして準備したのに恐縮ではあるが、環境を作らなくてもオンラインで試すことができるサービスがある。




 ここにはWEB上でpythonプログラムを作る環境があり、IDEでデバッグもできる
もちろんバックテストも可能だ。

 しかも、過去の相場データさらに財務データも使い放題、同じサーバーにあるので取得に時間もかからない。
 さらに掲示板があって自動売買プログラムについての情報交換がなされていたり、コンテストが開催されていたりする。
 これだけそろって無料。

残念なのは、全部英語でデータもすべて米国マーケット。

このサイトの日本版を作ったらニーズはあるのかな。無料で公開したいので誰かスポンサーになってください。

Quautopian
Quantopian
https://www.quantopian.com/home

2015年9月14日月曜日

日本の時系列株価データーがほしい時にはjsmを使う

もともとpandasで提供されているのは海外のyahoo financeから取得する株価で日本のyahoo financeはapi提供をしていなかったりする。

海外のデータだと今一つ親近感がわかないので、国内用のデータ取得モジュールを入れる。

jsm 0.18
Get the japanese stock market data

インストールはpipで問題なく簡単に入った

pip install jsm




import jsm と書いてテスト実行するとワーニングが出る。たぶん文字コードの問題かと思うけど実害はないので放置。

yahooの番号が4689なので、指定した期間のCSVを取得したいのであれば以下のようなプログラムを書いて実行する

#
import jsm
import datetime

start_date = datetime.date(2013,1,1)
end_date=datetime.date(2013,2,1)
c=jsm.QuotesCsv();
c.save_historical_prices("test.csv",4689,jsm.DAILY,start_date,end_date)

ちなみに日経平均株価は998407を指定すればいい。

2015年9月12日土曜日

PyAlgoTradeをUbuntuにインストールしてみる

 インストールばっかりで先に進んでないと思うけど、今度はCentOSではなくUbuntuにインストール。
いやね、レンタルサーバーだと最低スペックから少しでも上げると急激に値段が高くなる、しょせんメモリ2Gぐらいだったら手元に転がっているX61のほうが性能が高いことに気が付いた。メモリもDDR2なのでゴミみたいに扱われているしね。

 デスクトップはUbuntuのほうが圧倒的に楽。
標準のインストールを行った後、計算に必要なライブラリをapt-getでインストールする。Ubuntuではpipは使わないで、apt-get install python-モジュール名 で書くらしい。


sudo apt-get install python-numpy python-scipy python-matplotlib ipython ipython-notebook python-pandas python-sympy python-nose


計算関係のライブラリを入れたら、先ほどpipは使わないと書いていて恐縮だが、Pyalgotradeをpipで入れる。

pip install pyalgotrade


warningがいっぱい出るけど一応動く、そのうち動かなくなる予感なので、動作する今のバージョンで入れておくべき。

一通りいれたら、チュートリアルを試す。テスト方法を一切忘れていたのでブログを書いていてよかった。

やっぱり結果がその場でポップアップされるのは良い。

ta-libはpython で書かれたものとそれ以外があって

まず、これを実行し本体をコンパイルしてインストールする。
$ wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz
$ tar xvfz ta-lib-0.4.0-src.tar.gz
$ cd ta-lib-0.4.0
$ ./configure
$ make
$ make install
あとは呼び出すためのpythonライブラリをpipで入れる

pip ta-lib

ライブラリが見つからないといったエラーが出るので環境変数を設定する
$export LD_LIBRARY_PATH="/usr/local/lib:$LD_LIBRARY_PATH"