VWAP Momentum Trade

This sample is based on:
from pyalgotrade import strategy
from pyalgotrade import plotter
from pyalgotrade.tools import yahoofinance
from pyalgotrade.technical import vwap


class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument, vwapWindowSize):
        strategy.BacktestingStrategy.__init__(self, feed)
        self.__instrument = instrument
        self.__vwap = vwap.VWAP(feed[instrument], vwapWindowSize)

    def getVWAPDS(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 * 0.995 and notional > 0:
            self.marketOrder(self.__instrument, -100)
        elif price > vwap * 1.005 and notional < 1000000:
            self.marketOrder(self.__instrument, 100)


def main(plot):
    instrument = "aapl"
    vwapWindowSize = 5

    # Download the bars.
    feed = yahoofinance.build_feed([instrument], 2011, 2012, ".")

    myStrategy = MyStrategy(feed, instrument, vwapWindowSize)

    if plot:
        plt = plotter.StrategyPlotter(myStrategy, True, False, True)
        plt.getInstrumentSubplot(instrument).addDataSeries("vwap", myStrategy.getVWAPDS())

    myStrategy.run()
    print "Result: %.2f" % myStrategy.getResult()

    if plot:
        plt.plot()

if __name__ == "__main__":
    main(True)

this is what the output should look like:

2013-09-21 00:01:23,813 yahoofinance [INFO] Creating data directory
2013-09-21 00:01:23,814 yahoofinance [INFO] Downloading aapl 2011 to data/aapl-2011-yahoofinance.csv
2013-09-21 00:01:25,275 yahoofinance [INFO] Downloading aapl 2012 to data/aapl-2012-yahoofinance.csv
Result: 1436098.00

and this is what the plot should look like:

_images/vwap_momentum.png

you can get better returns by tunning the VWAP period as well as the entry and exit points.

Previous topic

Ernie Chan’s Gold vs. Gold Miners

Next topic

Bollinger Bands

This Page