呼び出すほうを工夫すれば無改造でかまわない。
今まで
オリジナルでは
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)