Exemple #1
0
    def testCumulativeReturn(self):
        initialCash = 33.06
        barFeed = yahoofeed.Feed()
        barFeed.addBarsFromCSV(
            AnalyzerTestCase.TestInstrument,
            common.get_data_file_path("orcl-2001-yahoofinance.csv"))
        strat = position_test.BaseTestStrategy(barFeed,
                                               AnalyzerTestCase.TestInstrument,
                                               initialCash)

        strat.addPosEntry(datetime.datetime(2001, 1, 12), strat.enterLong,
                          AnalyzerTestCase.TestInstrument, 1)  # 33.06
        strat.addPosExitMarket(datetime.datetime(2001, 11, 27))  # 14.32

        stratAnalyzer = returns.Returns(maxLen=10)
        strat.attachAnalyzer(stratAnalyzer)
        strat.run()
        self.assertTrue(
            round(strat.getBroker().getCash(), 2) == round(
                initialCash + (14.32 - 33.06), 2))
        self.assertTrue(
            round(33.06 *
                  (1 + stratAnalyzer.getCumulativeReturns()[-1]), 2) == 14.32)
        self.assertEqual(len(stratAnalyzer.getCumulativeReturns()), 10)
        self.assertEqual(len(stratAnalyzer.getReturns()), 10)
Exemple #2
0
    def testTwoBarReturns_CloseClose(self):
        initialCash = 15.90
        barFeed = yahoofeed.Feed()
        barFeed.setBarFilter(
            csvfeed.DateRangeFilter(datetime.datetime(2001, 12, 6),
                                    datetime.datetime(2001, 12, 7)))
        barFeed.addBarsFromCSV(
            AnalyzerTestCase.TestInstrument,
            common.get_data_file_path("orcl-2001-yahoofinance.csv"))
        strat = strategy_test.BaseStrategy(barFeed, initialCash)

        # 2001-12-06,15.61,16.03,15.50,15.90,66944900,15.55
        # 2001-12-07,15.74,15.95,15.55,15.91,42463200,15.56
        # Manually place the entry order, to get it filled on the first bar.
        order = strat.getBroker().createMarketOrder(
            broker.Order.Action.BUY, AnalyzerTestCase.TestInstrument, 1,
            True)  # Close: 15.90
        strat.getBroker().submitOrder(order)
        strat.addOrder(datetime.datetime(2001, 12, 6),
                       strat.getBroker().createMarketOrder,
                       broker.Order.Action.SELL,
                       AnalyzerTestCase.TestInstrument, 1,
                       True)  # Close: 15.91

        stratAnalyzer = returns.Returns()
        strat.attachAnalyzer(stratAnalyzer)
        strat.run()
        self.assertTrue(strat.getBroker().getCash() == initialCash +
                        (15.91 - 15.90))
        # First day returns: 0
        self.assertTrue(stratAnalyzer.getReturns()[0] == 0)
        # Second day returns: Open vs Prev. day's close
        self.assertTrue(stratAnalyzer.getReturns()[1] == (15.91 - 15.90) /
                        15.90)
Exemple #3
0
    def testOneBarReturn(self):
        initialCash = 1000
        barFeed = yahoofeed.Feed()
        barFeed.setBarFilter(
            csvfeed.DateRangeFilter(datetime.datetime(2001, 12, 7),
                                    datetime.datetime(2001, 12, 7)))
        barFeed.addBarsFromCSV(
            AnalyzerTestCase.TestInstrument,
            common.get_data_file_path("orcl-2001-yahoofinance.csv"))
        strat = strategy_test.BaseStrategy(barFeed, initialCash)

        # 2001-12-07,15.74,15.95,15.55,15.91,42463200,15.56
        # Manually place the orders to get them filled on the first (and only) bar.
        order = strat.getBroker().createMarketOrder(
            broker.Order.Action.BUY, AnalyzerTestCase.TestInstrument, 1,
            False)  # Open: 15.74
        strat.getBroker().submitOrder(order)
        order = strat.getBroker().createMarketOrder(
            broker.Order.Action.SELL, AnalyzerTestCase.TestInstrument, 1,
            True)  # Close: 15.91
        strat.getBroker().submitOrder(order)

        stratAnalyzer = returns.Returns()
        strat.attachAnalyzer(stratAnalyzer)
        strat.run()
        self.assertTrue(strat.getBroker().getCash() == initialCash +
                        (15.91 - 15.74))

        finalValue = 1000 - 15.74 + 15.91
        rets = (finalValue - initialCash) / float(initialCash)
        self.assertEqual(stratAnalyzer.getReturns()[-1], rets)
Exemple #4
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()
Exemple #5
0
from quantworks import plotter
from quantworks.barfeed import quandlfeed
from quantworks.stratanalyzer import returns
import sma_crossover

# Load the bar feed from the CSV file
feed = quandlfeed.Feed()
feed.addBarsFromCSV("orcl", "WIKI-ORCL-2000-quandl.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = sma_crossover.SMACrossOver(feed, "orcl", 20)

# Attach a returns analyzers to the strategy.
returnsAnalyzer = returns.Returns()
myStrategy.attachAnalyzer(returnsAnalyzer)

# Attach the plotter to the strategy.
plt = plotter.StrategyPlotter(myStrategy)
# Include the SMA in the instrument's subplot to get it displayed along with the closing prices.
plt.getInstrumentSubplot("orcl").addDataSeries("SMA", myStrategy.getSMA())
# Plot the simple returns on each bar.
plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())

# Run the strategy.
myStrategy.run()
myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())

# Plot the strategy.
plt.plot()