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




0 件のコメント:
コメントを投稿