def testFirstBar(self):
        initialCash = 1000
        barFeed = yahoofeed.Feed()
        barFeed.addBarsFromCSV(
            AnalyzerTestCase.TestInstrument,
            common.get_data_file_path("orcl-2001-yahoofinance.csv"))
        strat = strategy_test.TestStrategy(barFeed, initialCash)

        strat.addOrder(datetime.datetime(2001, 01, 02),
                       strat.getBroker().createMarketOrder,
                       broker.Order.Action.BUY,
                       AnalyzerTestCase.TestInstrument, 1,
                       False)  # 2001-01-03 Open: 25.25 Close: 32.00

        stratAnalyzer = returns.Returns()
        strat.attachAnalyzer(stratAnalyzer)
        strat.run()
        self.assertEqual(stratAnalyzer.getReturns()[0], 0)
        self.assertEqual(stratAnalyzer.getReturns()[1], (32.00 - 25.25) / 1000)

        # Check date times.
        datetimes = barFeed[AnalyzerTestCase.TestInstrument].getDateTimes()
        for i in [0, -1]:
            self.assertEqual(stratAnalyzer.getReturns().getDateTimes()[i],
                             datetimes[i])
            self.assertEqual(
                stratAnalyzer.getCumulativeReturns().getDateTimes()[i],
                datetimes[i])
    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.TestStrategy(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)
    def testTwoBarReturns_CloseClose(self):
        initialCash = 15.90
        barFeed = yahoofeed.Feed()
        barFeed.setBarFilter(
            csvfeed.DateRangeFilter(datetime.datetime(2001, 12, 06),
                                    datetime.datetime(2001, 12, 07)))
        barFeed.addBarsFromCSV(
            AnalyzerTestCase.TestInstrument,
            common.get_data_file_path("orcl-2001-yahoofinance.csv"))
        strat = strategy_test.TestStrategy(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, 06),
                       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)
    def testOneBarReturn(self):
        initialCash = 1000
        barFeed = yahoofeed.Feed()
        barFeed.setBarFilter(
            csvfeed.DateRangeFilter(datetime.datetime(2001, 12, 07),
                                    datetime.datetime(2001, 12, 07)))
        barFeed.addBarsFromCSV(
            AnalyzerTestCase.TestInstrument,
            common.get_data_file_path("orcl-2001-yahoofinance.csv"))
        strat = strategy_test.TestStrategy(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)
Beispiel #5
0
def testStrategy():
    from engine import bar

    strat = thrSMA
    instrument = '600288'
    market = 'SH'
    fromDate = '20150101'
    toDate ='20150601'
    frequency = bar.Frequency.MINUTE
    paras = [2, 20, 60, 10]
    plot = True

    #############################################path set ############################33
    import os
    print os.path.split(os.path.realpath(__file__))
    if frequency == bar.Frequency.MINUTE:
        path = os.path.join(os.environ.get('STRATEGYPATH'), '..', 'histdata', 'minute')
    elif frequency == bar.Frequency.DAY:
        path = os.path.join(os.environ.get('STRATEGYPATH'), '..', 'histdata', 'day')
    filepath = os.path.join(path, instrument + market + ".csv")


    #############################################don't change ############################33
    from engine.barfeed.csvfeed import Feed

    barfeed = Feed(frequency)
    barfeed.setDateTimeFormat('%Y-%m-%d %H:%M:%S')
    barfeed.loadBars(instrument, market, fromDate, toDate, filepath)

    engine_id = instrument + '.' + market
    strat = strat(barfeed, engine_id, *paras)

    from engine.stratanalyzer import returns
    from engine.stratanalyzer import sharpe
    from engine.stratanalyzer import drawdown
    from engine.stratanalyzer import trades

    retAnalyzer = returns.Returns()
    strat.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)
    drawDownAnalyzer = drawdown.DrawDown()
    strat.attachAnalyzer(drawDownAnalyzer)
    tradesAnalyzer = trades.Trades()
    strat.attachAnalyzer(tradesAnalyzer)

    strat.run()


    #夏普率
    sharp = sharpeRatioAnalyzer.getSharpeRatio(0.05)
    #最大回撤
    maxdd = drawDownAnalyzer.getMaxDrawDown()
    #收益率
    return_ = retAnalyzer.getCumulativeReturns()[-1]
    #收益曲线
    return_list = []
    for item in retAnalyzer.getCumulativeReturns():
        return_list.append(item)
    def testMultipleInstrumentsInterleaved(self):
        barFeed = yahoofeed.Feed()
        barFeed.addBarsFromCSV(
            "spy", common.get_data_file_path("spy-2010-yahoofinance.csv"),
            marketsession.NYSE.getTimezone())
        barFeed.addBarsFromCSV(
            "nikkei",
            common.get_data_file_path("nikkei-2010-yahoofinance.csv"),
            marketsession.TSE.getTimezone())

        strat = strategy_test.TestStrategy(barFeed, 1000)
        stratAnalyzer = returns.Returns()
        strat.attachAnalyzer(stratAnalyzer)

        strat.marketOrder("spy", 1)
        strat.run()
        # The cumulative return should be the same if we load nikkei or not.
        self.assertEqual(round(stratAnalyzer.getCumulativeReturns()[-1], 5),
                         0.01338)
    def testGoogle2011(self):
        initialValue = 1000000
        barFeed = yahoofeed.Feed()
        barFeed.addBarsFromCSV(
            AnalyzerTestCase.TestInstrument,
            common.get_data_file_path("goog-2011-yahoofinance.csv"))

        strat = strategy_test.TestStrategy(barFeed, initialValue)
        order = strat.getBroker().createMarketOrder(
            broker.Order.Action.BUY, AnalyzerTestCase.TestInstrument, 1654,
            True)  # 2011-01-03 close: 604.35
        strat.getBroker().submitOrder(order)

        stratAnalyzer = returns.Returns()
        strat.attachAnalyzer(stratAnalyzer)
        strat.run()
        finalValue = strat.getBroker().getEquity()

        self.assertEqual(
            round(stratAnalyzer.getCumulativeReturns()[-1], 4),
            round((finalValue - initialValue) / float(initialValue), 4))
Beispiel #8
0
def testStrategy():
    from engine import bar
    from engine import plotter
    
    strat = Bollinger_Bandit    
    instrument = '600288'
    market = 'SH'
    fromDate = '20150101'
    toDate ='20150601'
    frequency = bar.Frequency.MINUTE
    paras = [40, 15, 35, 15, 60, 2]
    plot = True
    
    #############################################path set ############################33 
    import os
    if frequency == bar.Frequency.MINUTE:
        path = os.path.join('..', 'histdata', 'minute')
    elif frequency == bar.Frequency.DAY:
        path = os.path.join('..', 'histdata', 'day')
    filepath = os.path.join(path, instrument + market + ".csv")
    
    
    #############################################don't change ############################33  
    from engine.barfeed.csvfeed import Feed
    
    barfeed = Feed(frequency)
    barfeed.setDateTimeFormat('%Y-%m-%d %H:%M:%S')
    barfeed.loadBars(instrument, market, fromDate, toDate, filepath)
    
    engine_id = instrument + '.' + market
    strat = strat(barfeed, engine_id, *paras)
    
    from engine.stratanalyzer import returns
    from engine.stratanalyzer import sharpe
    from engine.stratanalyzer import drawdown
    from engine.stratanalyzer import trades
    
    retAnalyzer = returns.Returns()
    strat.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)
    drawDownAnalyzer = drawdown.DrawDown()
    strat.attachAnalyzer(drawDownAnalyzer)
    tradesAnalyzer = trades.Trades()
    strat.attachAnalyzer(tradesAnalyzer)
    
    if plot:
        plt = plotter.StrategyPlotter(strat, True, True, True)
        
    strat.run()
    
    if plot:
        plt.plot()
        


    #夏普率
    sharp = sharpeRatioAnalyzer.getSharpeRatio(0.05)
    #最大回撤
    maxdd = drawDownAnalyzer.getMaxDrawDown()
    #收益率
    return_ = retAnalyzer.getCumulativeReturns()[-1]
    #收益曲线
    return_list = []
    for item in retAnalyzer.getCumulativeReturns():
        return_list.append(item)