呼び出すほうを工夫すれば無改造でかまわない。
今まで
オリジナルでは
plt.plot(None,None)改造したライブラリでは
plt.plot(None,None,"output.png")
としていたところを、以下の2行でいい
fig=plt.buildFigure(None,None) fig.savefig("output.png")
いい加減な情報を提供して申し訳ない。
plt.plot(None,None)改造したライブラリでは
plt.plot(None,None,"output.png")
fig=plt.buildFigure(None,None) fig.savefig("output.png")
#!/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")
#/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()
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()
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)
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)
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)
from pyalgotrade import strategy from pyalgotrade.technical import ma from pyalgotrade.technical import cross class SMACrossOver(strategy.BacktestingStrategy): def __init__(self, feed, instrument, smaPeriod): strategy.BacktestingStrategy.__init__(self, feed) self.__instrument = instrument self.__position = None # We'll use adjusted close values instead of regular close values. self.setUseAdjustedValues(True) self.__prices = feed[instrument].getPriceDataSeries() self.__sma = ma.SMA(self.__prices, smaPeriod) def getSMA(self): return self.__sma def onEnterCanceled(self, position): self.__position = None def onExitOk(self, position): self.__position = None def onExitCanceled(self, position): # If the exit was canceled, re-submit it. self.__position.exitMarket() def onBars(self, bars): # If a position was not opened, check if we should enter a long position. if self.__position is None: if cross.cross_above(self.__prices, self.__sma) > 0: shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice()) # Enter a buy market order. The order is good till canceled. self.__position = self.enterLong(self.__instrument, shares, True) # Check if we have to exit the position. elif not self.__position.exitActive() and cross.cross_below(self.__prices, self.__sma) > 0: self.__position.exitMarket()
import matplotlib matplotlib.use('Agg') import sma_crossover from pyalgotrade import plotter from pyalgotrade.tools import yahoofinance from pyalgotrade.stratanalyzer import sharpe def main(plot): instrument = "aapl" smaPeriod = 163 # Download the bars. feed = yahoofinance.build_feed([instrument], 2011, 2012, ".") strat = sma_crossover.SMACrossOver(feed, instrument, smaPeriod) sharpeRatioAnalyzer = sharpe.SharpeRatio() strat.attachAnalyzer(sharpeRatioAnalyzer) if plot: plt = plotter.StrategyPlotter(strat, True, False, True) plt.getInstrumentSubplot(instrument).addDataSeries("sma", strat.getSMA()) strat.run() print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05) if plot: plt.plot(None,None,"output.png") if __name__ == "__main__": main(True)
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 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 def getVWAP(self): return self.__vwap def onBars(self, bars): vwap = self.__vwap[-1] if vwap is None: return shares = self.getBroker().getShares(self.__instrument) price = bars[self.__instrument].getClose() notional = shares * price 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(plot): instrument = "aapl" vwapWindowSize = 5 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) if plot: plt = plotter.StrategyPlotter(strat, True, False, True) plt.getInstrumentSubplot(instrument).addDataSeries("vwap", strat.getVWAP()) strat.run() print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05) if plot: plt.plot(None,None,"output.png") if __name__ == "__main__": main(True)
VWAPの重要な3つの機能
VWAPの重要な機能として、以下の3点があると言えます。
- 市場参加者の強気・弱気を判断する
- 抵抗線、支持線として機能する
- ファンド(正確には証券会社)などが買いを入れる(VWAP取引)基準として使用する
1 市場参加者の強気・弱気を判断する
ちなみに株価がVWAPを上回っている状態では、今日買った人全員の損益を合計したらプラスで、逆に株価がVWAPを下回っている場合はマイナスだ、ということがわかります。つまり、株価がVWAPを上回っている時には、短期的には強含みでその後も買い目線が続くだろうと判断できるわけです。逆に下回る時なんかは弱含みとなり、買いの手は控えようと考える投資家がおおくなるため、軟調に推移することが多くなります。
2 抵抗線、支持線として機能する
また、VWAPには抵抗・支持というその先の付近に株価が近づくと跳ね返されるという機能があります。
当然VWAPを見てトレードをしている人がおおく、VWAPトレーダーと呼ばれる「VWAPに近づくと買いを入れる」トレーダーも多く存在するため(後述)、その付近ではいったん株価は反発することになります。
そのことを知っておけば、移動平均線やトレンドラインにもう1つ抵抗・支持の役割をもつ指標を自分のトレードの手法の一つとして持っておくことができますよね。
3 ファンド(正確には証券会社)などが買いを入れる(VWAP取引)基準として使用する
ファンドや投資家などが市場で買いを入れると、多量の注文の場合はマーケットインパクトが大きくなって市場に混乱をきたします。そのため、そのような大口の注文は証券会社などによって上手に捌いてもらう必要が有るのです。
そしてそのために使用されるのがこれまで説明してきたVWAPであり、このような取引をVWAP取引といいます。
「今日のATRがいくらなのかは、すぐに計算できます。計算に使う数字は前日の終値と、今日の高値・安値だけです」動画も日本語に
ATRの計算って、意外と簡単。まずは今日のTR(トゥルー・レンジ)を求める。TRは次の3つの数字のうち、最大のものだ。
(1)当日高値-前日終値(2)前日終値-当日安値(3)当日高値-当日安値 この3つの数字のなかで最大のものが「今日のTR」。当日を含め過去20日分のTRを平均化するとATRとなる。エクセルに計算式を入力しておくと、日々の四本値を入れるだけで計算できて便利かも。
ROCは前ページで解説したモメンタムの改良版です。モメンタムでは、本日と〇日前の単純な値差をプロットしていきます。そのため、表示する期間や銘柄の違いで値動きの幅が異なれば、目盛りの間隔も異なってきます。また、月足で長期間の動向を見る場合、初めのほうと終わりのほうで相場の水準が大きく異なると、見た目で比較することができません
そのため、絶対的な値差ではなく変化率をプロットすればよいという考え方が出てきます。これがROC(Rate of Change)です。計算式は次のようになります。
- 本日のROC = (本日のレート ÷ 〇日前のレート) × 100
#!/usr/bin/python # -*- coding: utf-8 -*- import logging from pyalgotrade.technical import highlow from pyalgotrade import strategy from pyalgotrade.barfeed import yahoofeed from pyalgotrade.technical import cross logging.basicConfig(filename='/tmp/exec.log') 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 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()
2000-11-27 00:00:00 strategy [INFO] 23.125000 Hi:28.875 Lo:22.3125 2000-11-28 00:00:00 strategy [INFO] 22.656250 Hi:28.875 Lo:22.3125 2000-11-29 00:00:00 strategy [INFO] 22.875000 Hi:28.875 Lo:22.3125 2000-11-30 00:00:00 strategy [INFO] 26.500000 Hi:28.8125 Lo:22.3125 2000-12-01 00:00:00 strategy [INFO] 26.437500 Hi:28.8125 Lo:22.3125 2000-12-04 00:00:00 strategy [INFO] 28.187500 Hi:28.1875 Lo:22.3125 2000-12-05 00:00:00 strategy [INFO] 31.500000 Hi:31.5 Lo:22.3125 2000-12-06 00:00:00 strategy [INFO] 30.187500 Hi:31.5 Lo:22.3125 2000-12-07 00:00:00 strategy [INFO] 28.312500 Hi:31.5 Lo:22.65625 2000-12-08 00:00:00 strategy [INFO] 30.062500 Hi:31.5 Lo:22.65625 2000-12-11 00:00:00 strategy [INFO] 31.937500 Hi:31.9375 Lo:22.65625 2000-12-12 00:00:00 strategy [INFO] 30.750000 Hi:31.9375 Lo:22.875 2000-12-13 00:00:00 strategy [INFO] 28.375000 Hi:31.9375 Lo:26.4375 2000-12-14 00:00:00 strategy [INFO] 27.500000 Hi:31.9375 Lo:26.4375 2000-12-15 00:00:00 strategy [INFO] 28.562500 Hi:31.9375 Lo:27.5 2000-12-18 00:00:00 strategy [INFO] 32.000000 Hi:32.0 Lo:27.5 2000-12-19 00:00:00 strategy [INFO] 30.625000 Hi:32.0 Lo:27.5 2000-12-20 00:00:00 strategy [INFO] 28.500000 Hi:32.0 Lo:27.5 2000-12-21 00:00:00 strategy [INFO] 29.500000 Hi:32.0 Lo:27.5 2000-12-22 00:00:00 strategy [INFO] 31.875000 Hi:32.0 Lo:27.5 2000-12-26 00:00:00 strategy [INFO] 30.937500 Hi:32.0 Lo:27.5
#!/usr/bin/python # -*- coding: utf-8 -*- import logging from pyalgotrade.technical import ma from pyalgotrade import strategy from pyalgotrade.barfeed import yahoofeed from pyalgotrade.technical import cross logging.basicConfig(filename='/tmp/exec.log') class MyStrategy(strategy.BacktestingStrategy): def __init__(self, feed, instrument): strategy.BacktestingStrategy.__init__(self, feed) self.__prices = feed[instrument].getPriceDataSeries() self.__sma = ma.SMA(feed[instrument].getCloseDataSeries(), 15) self.__instrument = instrument def onBars(self, bars): if self.__sma[-1] is None: return bar = bars[self.__instrument] flag1 = 1 if self.__prices[-1] > self.__sma[-1] else 0 flag2 = cross.cross_above(self.__prices,self.__sma) self.info("%f %f SMA:%f %d %d " % (bar.getClose(),self.__prices[-1],self.__sma[-1],flag1,flag2)) # 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()
2000-11-14 00:00:00 strategy [INFO] 28.375000 28.375000 SMA:29.570833 0 0 2000-11-15 00:00:00 strategy [INFO] 28.875000 28.875000 SMA:29.204167 0 0 2000-11-16 00:00:00 strategy [INFO] 27.375000 27.375000 SMA:28.758333 0 0 2000-11-17 00:00:00 strategy [INFO] 28.812500 28.812500 SMA:28.400000 1 1 2000-11-20 00:00:00 strategy [INFO] 24.750000 24.750000 SMA:27.941667 0 0 2000-11-21 00:00:00 strategy [INFO] 23.875000 23.875000 SMA:27.333333 0 0 2000-11-22 00:00:00 strategy [INFO] 22.312500 22.312500 SMA:26.729167 0 0 2000-11-24 00:00:00 strategy [INFO] 24.125000 24.125000 SMA:26.366667 0 0 2000-11-27 00:00:00 strategy [INFO] 23.125000 23.125000 SMA:25.887500 0 0 2000-11-28 00:00:00 strategy [INFO] 22.656250 22.656250 SMA:25.535417 0 0 2000-11-29 00:00:00 strategy [INFO] 22.875000 22.875000 SMA:25.289583 0 0 2000-11-30 00:00:00 strategy [INFO] 26.500000 26.500000 SMA:25.402083 1 1 2000-12-01 00:00:00 strategy [INFO] 26.437500 26.437500 SMA:25.352083 1 0 2000-12-04 00:00:00 strategy [INFO] 28.187500 28.187500 SMA:25.535417 1 0 2000-12-05 00:00:00 strategy [INFO] 31.500000 31.500000 SMA:25.985417 1 0 2000-12-06 00:00:00 strategy [INFO] 30.187500 30.187500 SMA:26.106250 1 0 2000-12-07 00:00:00 strategy [INFO] 28.312500 28.312500 SMA:26.068750 1 0 2000-12-08 00:00:00 strategy [INFO] 30.062500 30.062500 SMA:26.247917 1 0 2000-12-11 00:00:00 strategy [INFO] 31.937500 31.937500 SMA:26.456250 1 0 2000-12-12 00:00:00 strategy [INFO] 30.750000 30.750000 SMA:26.856250 1 0 2000-12-13 00:00:00 strategy [INFO] 28.375000 28.375000 SMA:27.156250 1 0 2000-12-14 00:00:00 strategy [INFO] 27.500000 27.500000 SMA:27.502083 0 0 2000-12-15 00:00:00 strategy [INFO] 28.562500 28.562500 SMA:27.797917 1 1 2000-12-18 00:00:00 strategy [INFO] 32.000000 32.000000 SMA:28.389583 1 0 2000-12-19 00:00:00 strategy [INFO] 30.625000 30.625000 SMA:28.920833 1 0 2000-12-20 00:00:00 strategy [INFO] 28.500000 28.500000 SMA:29.295833 0 0 2000-12-21 00:00:00 strategy [INFO] 29.500000 29.500000 SMA:29.495833 1 1 2000-12-22 00:00:00 strategy [INFO] 31.875000 31.875000 SMA:29.858333 1 0 2000-12-26 00:00:00 strategy [INFO] 30.937500 30.937500 SMA:30.041667 1 0 2000-12-27 00:00:00 strategy [INFO] 30.687500 30.687500 SMA:29.987500 1 0 2000-12-28 00:00:00 strategy [INFO] 31.062500 31.062500 SMA:30.045833 1 0 2000-12-29 00:00:00 strategy [INFO] 29.062500 29.062500 SMA:30.095833 0 0
#!/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()
モメンタム投資とは、現在の株価のトレンドが継続することを想定した投資ストラテジーです
#!/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()
#!/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()
#!/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()
#!/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などのモメンタムかな。
class MyStrategy(strategy.BacktestingStrategy): def __init__(self, feed, instrument): pass def onBars(self, bars): pass feed = yahoofeed.Feed() myStrategy = MyStrategy(feed, "orcl") myStrategy.run()
#!/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()当日分のデータだけだと、値段と取引量の絶対値と陽線か陰線かしかわからない。
#!/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に変わっている。
pip install jsm
# 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)
sudo apt-get install python-numpy python-scipy python-matplotlib ipython ipython-notebook python-pandas python-sympy python-nose
pip install pyalgotrade
$ 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で入れるimport numpy import talib data=numpy.random.random(100) upper,middle,lower = talib.BBANDS(data,matype=talib.MA_Type.T3) print(upper) print(middle) print(lower)TA-Libがサポートしている指標は以下の通り。すいません、半分もわかりません。www