基本のプログラムを最小限のものに絞り込みます。
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になるので実数として表示できないからだ。
この後は指標をいろいろ試してみようかな。
0 件のコメント:
コメントを投稿