Ejemplo n.º 1
0
def main(plot):
    instruments = ["gld", "gdx"]
    windowSize = 50

    # Load the bars. These files were manually downloaded from Yahoo Finance.
    feed = yahoofeed.Feed()
    for year in range(2006, 2012 + 1):
        for instrument in instruments:
            fileName = "%s-%d-yahoofinance.csv" % (instrument, year)
            print("Loading bars from %s" % fileName)
            feed.addBarsFromCSV(instrument, fileName)

    strat = StatArb(feed, instruments[0], instruments[1], windowSize)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, False, False, True)
        plt.getOrCreateSubplot("hedge").addDataSeries("Hedge Ratio",
                                                      strat.getHedgeRatioDS())
        plt.getOrCreateSubplot("spread").addDataSeries("Spread",
                                                       strat.getSpreadDS())

    strat.run()
    print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05))

    if plot:
        plt.plot()
Ejemplo n.º 2
0
    def __testIGE_BrokerImpl(self, quantity):
        initialCash = 42.09 * quantity
        # This testcase is based on an example from Ernie Chan's book:
        # 'Quantitative Trading: How to Build Your Own Algorithmic Trading Business'
        barFeed = yahoofeed.Feed()
        barFeed.addBarsFromCSV(
            "ige", common.get_data_file_path("sharpe-ratio-test-ige.csv"))
        strat = strategy_test.BaseStrategy(barFeed, initialCash)
        strat.setUseAdjustedValues(True)
        strat.setBrokerOrdersGTC(True)
        stratAnalyzer = sharpe.SharpeRatio()
        strat.attachAnalyzer(stratAnalyzer)

        # Disable volume checks to match book results.
        strat.getBroker().getFillStrategy().setVolumeLimit(None)

        # Manually place the order to get it filled on the first bar.
        order = strat.getBroker().createMarketOrder(broker.Order.Action.BUY,
                                                    "ige", quantity,
                                                    True)  # Adj. Close: 42.09
        order.setGoodTillCanceled(True)
        strat.getBroker().submitOrder(order)
        strat.addOrder(datetime.datetime(2007, 11, 13),
                       strat.getBroker().createMarketOrder,
                       broker.Order.Action.SELL, "ige", quantity,
                       True)  # Adj. Close: 127.64
        strat.run()
        self.assertEqual(round(strat.getBroker().getCash(), 2),
                         initialCash + (127.64 - 42.09) * quantity)
        self.assertEqual(strat.orderUpdatedCalls, 6)
        # The results are slightly different only because I'm taking into account the first bar as well.
        self.assertEqual(round(stratAnalyzer.getSharpeRatio(0.04, True), 4),
                         0.7889)
        self.assertEqual(round(stratAnalyzer.getSharpeRatio(0.04, False), 4),
                         0.0497)
Ejemplo n.º 3
0
    def testIntraDay(self):
        barFeed = ninjatraderfeed.Feed(ninjatraderfeed.Frequency.MINUTE,
                                       marketsession.USEquities.getTimezone())
        barFeed.setBarFilter(csvfeed.USEquitiesRTH())
        barFeed.addBarsFromCSV(
            "spy", common.get_data_file_path("nt-spy-minute-2011.csv"))
        strat = strategy_test.BaseStrategy(barFeed, 1000)
        stratAnalyzer = sharpe.SharpeRatio(False)
        strat.attachAnalyzer(stratAnalyzer)
        strat.marketOrder("spy", 1)

        strat.run()

        tradingPeriods = 252 * 6.5 * 60
        manualAnnualized = sharpe.sharpe_ratio(stratAnalyzer.getReturns(),
                                               0.04, tradingPeriods, True)
        manualNotAnnualized = sharpe.sharpe_ratio(stratAnalyzer.getReturns(),
                                                  0.04, tradingPeriods, False)
        analyzerAnnualized = stratAnalyzer.getSharpeRatio(0.04)
        analyzerNotAnnualized = stratAnalyzer.getSharpeRatio(0.04, False)

        self.assertEqual(round(analyzerAnnualized, 10), -1.1814830854)
        self.assertEqual(round(analyzerNotAnnualized, 10), -0.0037659686)
        # They should be similar, but not identical because the analyzer uses 365 days/year
        # when useDailyReturns is set to False.
        self.assertEqual(round(analyzerAnnualized, 1),
                         round(manualAnnualized, 1))
        self.assertEqual(round(analyzerNotAnnualized, 3),
                         round(manualNotAnnualized, 3))
Ejemplo n.º 4
0
def main(plot):
    instrument = "yhoo"
    bBandsPeriod = 40

    # Download the bars.
    feed = quandl.build_feed("WIKI", [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()
Ejemplo n.º 5
0
    def testNoTrades(self):
        barFeed = yahoofeed.Feed()
        barFeed.addBarsFromCSV(
            "ige", common.get_data_file_path("sharpe-ratio-test-ige.csv"))
        strat = strategy_test.BaseStrategy(barFeed, 1000)
        stratAnalyzer = sharpe.SharpeRatio()
        strat.attachAnalyzer(stratAnalyzer)

        strat.run()
        self.assertTrue(strat.getBroker().getCash() == 1000)
        self.assertTrue(stratAnalyzer.getSharpeRatio(0.04, True) == 0)
        self.assertTrue(stratAnalyzer.getSharpeRatio(0) == 0)
        self.assertTrue(stratAnalyzer.getSharpeRatio(0, True) == 0)
Ejemplo n.º 6
0
def main(plot):
    initialCash = 10000
    instrumentsByClass = {
        "US Stocks": ["VTI"],
        "Foreign Stocks": ["VEU"],
        "US 10 Year Government Bonds": ["IEF"],
        "Real Estate": ["VNQ"],
        "Commodities": ["DBC"],
    }

    # Load the bars. These files were manually downloaded from Yahoo Finance.
    feed = yahoofeed.Feed()
    instruments = ["SPY"]
    for assetClass in instrumentsByClass:
        instruments.extend(instrumentsByClass[assetClass])

    for year in range(2007, 2013+1):
        for instrument in instruments:
            fileName = "%s-%d-yahoofinance.csv" % (instrument, year)
            print("Loading bars from %s" % fileName)
            feed.addBarsFromCSV(instrument, fileName)

    # Build the strategy and attach some metrics.
    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()
Ejemplo n.º 7
0
def main(plot):
    instrument = "AAPL"
    smaPeriod = 163

    # Download the bars.
    feed = quandl.build_feed("WIKI", [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()
Ejemplo n.º 8
0
def main(plot):
    instrument = "AAPL"
    vwapWindowSize = 5
    threshold = 0.01

    # Download the bars.
    feed = quandl.build_feed("WIKI", [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()
Ejemplo n.º 9
0
def main(plot):
    instrument = "DIA"
    entrySMA = 200
    exitSMA = 5
    rsiPeriod = 2
    overBoughtThreshold = 90
    overSoldThreshold = 10

    # Load the bars. These files were manually downloaded from Yahoo Finance.
    feed = yahoofeed.Feed()
    for year in range(2009, 2013):
        fileName = "%s-%d-yahoofinance.csv" % (instrument, year)
        print("Loading bars from %s" % fileName)
        feed.addBarsFromCSV(instrument, fileName)

    strat = rsi2.RSI2(feed, instrument, entrySMA, exitSMA, rsiPeriod,
                      overBoughtThreshold, overSoldThreshold)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, False, 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()
Ejemplo n.º 10
0
        pass


# Load the bar feed from the CSV file
feed = quandlfeed.Feed()
feed.addBarsFromCSV("ibm", "WIKI-IBM-2011-quandl.csv")
feed.addBarsFromCSV("aes", "WIKI-AES-2011-quandl.csv")
feed.addBarsFromCSV("aig", "WIKI-AIG-2011-quandl.csv")
feed.addBarsFromCSV("orcl", "WIKI-ORCL-2011-quandl.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed)

# Attach returns and sharpe ratio analyzers.
retAnalyzer = returns.Returns()
myStrategy.attachAnalyzer(retAnalyzer)
sharpeRatioAnalyzer = sharpe.SharpeRatio()
myStrategy.attachAnalyzer(sharpeRatioAnalyzer)

# Run the strategy
myStrategy.run()

# Print the results.
print("Final portfolio value: $%.2f" % myStrategy.getResult())
print("Anual return: %.2f %%" % (retAnalyzer.getCumulativeReturns()[-1] * 100))
print("Average daily return: %.2f %%" %
      (stats.mean(retAnalyzer.getReturns()) * 100))
print("Std. dev. daily return: %.4f" %
      (stats.stddev(retAnalyzer.getReturns())))
print("Sharpe ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0)))