def testCumulativeReturn(self): initialCash = 33.06 barFeed = googlefeed.Feed() barFeed.addBarsFromCSV( AnalyzerTestCase.TestInstrument, common.get_data_file_path("orcl-2001-googlefinance.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 testOneBarReturn(self): initialCash = 1000 barFeed = googlefeed.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-googlefinance.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)
def testTwoBarReturns_CloseClose(self): initialCash = 15.90 barFeed = googlefeed.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-googlefinance.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 __getFeed(self): # Load the feed and process all bars. barFeed = googlefeed.Feed() barFeed.addBarsFromCSV( VWAPTestCase.Instrument, common.get_data_file_path("orcl-2001-googlefinance.csv")) return barFeed
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 = googlefeed.Feed() barFeed.addBarsFromCSV( "ige", common.get_data_file_path("sharpe-ratio-test-ige.csv")) strat = strategy_test.TestStrategy(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)
def testLoadDailyBars(self): tmpFeed = TemporarySQLiteFeed(SQLiteFeedTestCase.dbName, bar.Frequency.DAY) with tmpFeed: # Load bars using a Google feed. googleFeed = googlefeed.Feed() googleFeed.addBarsFromCSV("orcl", common.get_data_file_path("orcl-2000-googlefinance.csv"), marketsession.USEquities.timezone) googleFeed.addBarsFromCSV("orcl", common.get_data_file_path("orcl-2001-googlefinance.csv"), marketsession.USEquities.timezone) # Fill the database using the bars from the Google feed. sqliteFeed = tmpFeed.getFeed() sqliteFeed.getDatabase().addBarsFromFeed(googleFeed) # Load the SQLite feed and process all bars. sqliteFeed.loadBars("orcl") for bars in sqliteFeed: pass # Check that both dataseries have the same bars. googleDS = googleFeed["orcl"] sqliteDS = sqliteFeed["orcl"] self.assertEqual(len(googleDS), len(sqliteDS)) for i in xrange(len(googleDS)): self.assertEqual(googleDS[i].getDateTime(), sqliteDS[i].getDateTime()) self.assertEqual(googleDS[i].getOpen(), sqliteDS[i].getOpen()) self.assertEqual(googleDS[i].getHigh(), sqliteDS[i].getHigh()) self.assertEqual(googleDS[i].getLow(), sqliteDS[i].getLow()) self.assertEqual(googleDS[i].getClose(), sqliteDS[i].getClose()) self.assertEqual(googleDS[i].getAdjClose(), sqliteDS[i].getAdjClose())
def testBounded(self): tmpFeed = TemporarySQLiteFeed(SQLiteFeedTestCase.dbName, bar.Frequency.DAY, maxLen=2) with tmpFeed: # Load bars using a Google feed. googleFeed = googlefeed.Feed(maxLen=1) googleFeed.addBarsFromCSV("orcl", common.get_data_file_path("orcl-2000-googlefinance.csv"), marketsession.USEquities.timezone) googleFeed.addBarsFromCSV("orcl", common.get_data_file_path("orcl-2001-googlefinance.csv"), marketsession.USEquities.timezone) # Fill the database using the bars from the Google feed. sqliteFeed = tmpFeed.getFeed() sqliteFeed.getDatabase().addBarsFromFeed(googleFeed) # Load the SQLite feed and process all bars. sqliteFeed.loadBars("orcl") for bars in sqliteFeed: pass barDS = sqliteFeed["orcl"] self.assertEqual(len(barDS), 2) self.assertEqual(len(barDS.getDateTimes()), 2) self.assertEqual(len(barDS.getCloseDataSeries()), 2) self.assertEqual(len(barDS.getCloseDataSeries().getDateTimes()), 2) self.assertEqual(len(barDS.getOpenDataSeries()), 2) self.assertEqual(len(barDS.getHighDataSeries()), 2) self.assertEqual(len(barDS.getLowDataSeries()), 2) self.assertEqual(len(barDS.getAdjCloseDataSeries()), 2)
def testResampledBarFeed(self): barFeed = googlefeed.Feed() barFeed.addBarsFromCSV( "spy", common.get_data_file_path("spy-2010-googlefinance.csv")) barFeed.addBarsFromCSV( "nikkei", common.get_data_file_path("nikkei-2010-googlefinance.csv")) resampledBarFeed = resampled_bf.ResampledBarFeed( barFeed, bar.Frequency.MONTH) disp = dispatcher.Dispatcher() disp.addSubject(barFeed) disp.addSubject(resampledBarFeed) disp.run() weeklySpyBarDS = resampledBarFeed["spy"] weeklyNikkeiBarDS = resampledBarFeed["nikkei"] # Check first bar self.assertEqual(weeklySpyBarDS[0].getDateTime().date(), datetime.date(2010, 1, 1)) self.assertEqual(weeklyNikkeiBarDS[0].getDateTime().date(), datetime.date(2010, 1, 1)) # Check last bar self.assertEqual(weeklySpyBarDS[-1].getDateTime().date(), datetime.date(2010, 11, 1)) self.assertEqual(weeklyNikkeiBarDS[-1].getDateTime().date(), datetime.date(2010, 11, 1))
def testFirstBar(self): initialCash = 1000 barFeed = googlefeed.Feed() barFeed.addBarsFromCSV( AnalyzerTestCase.TestInstrument, common.get_data_file_path("orcl-2001-googlefinance.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 __init__(self, instruments, initialCash, fromYear, toYear, debugMode=True, csvStorage="./googlefinance", filterInvalidRows=True): self.__logger = logger.getLogger(GoogleFinanceBacktest.LOGGER_NAME) self.__finalPortfolioValue = 0 # Create Feed self.__feed = googlefeed.Feed() rowFilter = lambda row: row["Close"] == "-" or row["Open"] == "-" or row["High"] == "-" or row["Low"] == "-" or \ row["Volume"] == "-" self.__feed = googlefinance.build_feed( instruments, fromYear, toYear, storage=csvStorage, skipErrors=True, rowFilter=rowFilter if filterInvalidRows else None) # Create Broker comissionModel = backtesting.FixedPerTrade(10) self.__broker = backtesting.Broker(initialCash, self.__feed, commission=comissionModel) self.__strategy = TradingSystem(self.__feed, self.__broker, debugMode=debugMode) # Create Analyzers returnsAnalyzer = returns.Returns() self.__strategy.attachAnalyzer(returnsAnalyzer) dailyResultsAnalyzer = DailyTradingResults() self.__strategy.attachAnalyzer(dailyResultsAnalyzer) self.__tradesAnalyzer = Trades() self.__strategy.attachAnalyzer(self.__tradesAnalyzer) # Create plotters self.__plotters = [] self.__plotters.append( plotter.StrategyPlotter(self.__strategy, plotAllInstruments=False, plotPortfolio=True, plotBuySell=False)) self.__plotters[0].getOrCreateSubplot("returns").addDataSeries( "Simple returns", returnsAnalyzer.getReturns()) self.__plotters[0].getOrCreateSubplot("dailyresult").addDataSeries( "Daily Results", dailyResultsAnalyzer.getTradeResults()) for i in range(0, len(instruments)): p = plotter.StrategyPlotter(self.__strategy, plotAllInstruments=False, plotPortfolio=False) p.getInstrumentSubplot(instruments[i]) self.__plotters.append(p)
def testParseFile(self): bf = googlefeed.Feed() bf.addBarsFromCSV(INSTRUMENT, common.get_data_file_path("orcl-2010-googlefinance.csv")) bf.loadAll() ds = bf.getDataSeries(INSTRUMENT) self.assertEqual(ds[-1].getOpen(), 31.22) self.assertEqual(ds[-1].getClose(), 31.30) self.assertEqual(ds[-1].getDateTime(), datetime.datetime(2010, 12, 31))
def __test(self, strategyClass, finalValue): feed = googlefeed.Feed() feed.addBarsFromCSV( "orcl", common.get_data_file_path("orcl-2001-googlefinance.csv")) myStrategy = strategyClass(feed, 10, 25) myStrategy.run() myStrategy.printDebug("Final result:", round(myStrategy.getFinalValue(), 2)) self.assertTrue(round(myStrategy.getFinalValue(), 2) == finalValue)
def testNoEvents(self): feed = googlefeed.Feed() feed.addBarsFromCSV( "orcl", common.get_data_file_path("orcl-2000-googlefinance.csv")) predicate = Predicate([]) eventProfiler = eventprofiler.Profiler(predicate, 5, 5) eventProfiler.run(feed, True) self.assertEqual(eventProfiler.getResults().getEventCount(), 0)
def run_strategy(smaPeriod): # Load the Google feed from the CSV file feed = googlefeed.Feed() feed.addBarsFromCSV("ytlpowr", "dataset/6742.kl.csv") # Evaluate the strategy with the feed's bars. myStrategy = strategy.SmaTradingStrategy(feed, "ytlpowr", smaPeriod) myStrategy.run() print("Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity())
def testParseFile(self): instrument = "orcl" bf = googlefeed.Feed() bf.addBarsFromCSV(instrument, common.get_data_file_path("orcl-2010-googlefinance.csv")) bf.loadAll() self.assertEqual(bf[instrument][-1].getOpen(), 31.22) self.assertEqual(bf[instrument][-1].getClose(), 31.30) self.assertEqual(bf[instrument][-1].getDateTime(), datetime.datetime(2010, 12, 31))
def run_strategy(smaPeriod): # Load the google feed from the CSV file feed = googlefeed.Feed() feed.addBarsFromCSV("orcl", "orcl-2000.csv") # Evaluate the strategy with the feed. myStrategy = MyStrategy(feed, "orcl", smaPeriod) myStrategy.run() print "Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity()
def build_feed(instruments, fromYear, toYear, storage, frequency=bar.Frequency.DAY, timezone=None, skipErrors=False): """Build and load a :class:`pyalgotrade.barfeed.googlefeed.Feed` using CSV files downloaded from Google Finance. CSV files are downloaded if they haven't been downloaded before. :param instruments: Instrument identifiers. :type instruments: list. :param fromYear: The first year. :type fromYear: int. :param toYear: The last year. :type toYear: int. :param storage: The path were the files will be loaded from, or downloaded to. :type storage: string. :param frequency: The frequency of the bars. Only **pyalgotrade.bar.Frequency.DAY** is currently supported. :param timezone: The default timezone to use to localize bars. Check :mod:`pyalgotrade.marketsession`. :type timezone: A pytz timezone. :param skipErrors: True to keep on loading/downloading files in case of errors. :type skipErrors: boolean. :rtype: :class:`pyalgotrade.barfeed.googlefeed.Feed`. """ logger = pyalgotrade.logger.getLogger("googlefinance") ret = googlefeed.Feed(frequency, timezone) if not os.path.exists(storage): logger.info("Creating {dirname} directory".format(dirname=storage)) os.mkdir(storage) for year in range(fromYear, toYear + 1): for instrument in instruments: fileName = os.path.join( storage, "{instrument}-{year}-googlefinance.csv".format( instrument=instrument, year=year)) if not os.path.exists(fileName): logger.info( "Downloading {instrument} {year} to {filename}".format( instrument=instrument, year=year, filename=fileName)) try: if frequency == bar.Frequency.DAY: download_daily_bars(instrument, year, fileName) else: raise Exception("Invalid frequency") except Exception as e: if skipErrors: logger.error(str(e)) continue else: raise e ret.addBarsFromCSV(instrument, fileName) return ret
def testDownloadAndParseDaily(self): instrument = "orcl" common.init_temp_path() path = os.path.join(common.get_temp_path(), "orcl-2010.csv") googlefinance.download_daily_bars(instrument, 2010, path) bf = googlefeed.Feed() bf.addBarsFromCSV(instrument, path) bf.loadAll() self.assertEqual(bf[instrument][-1].getOpen(), 31.22) self.assertEqual(bf[instrument][-1].getClose(), 31.30)
def testFailingStrategy(self): barFeed = googlefeed.Feed() instrument = "orcl" barFeed.addBarsFromCSV( instrument, common.get_data_file_path("orcl-2000-googlefinance.csv")) res = local.run(FailingStrategy, barFeed, parameters_generator(instrument, 5, 100), logLevel=logging.DEBUG) self.assertIsNone(res)
def testOneEvent(self): feed = googlefeed.Feed() feed.addBarsFromCSV( "orcl", common.get_data_file_path("orcl-2000-googlefinance.csv")) predicate = Predicate([datetime.date(2000, 1, 11)]) eventProfiler = eventprofiler.Profiler(predicate, 5, 5) eventProfiler.run(feed, True) self.assertEqual(eventProfiler.getResults().getEventCount(), 1) self.assertEqual(eventProfiler.getResults().getValues(0)[0], 1.0) self.assertEqual(round(eventProfiler.getResults().getValues(5)[0], 5), round(1.016745541, 5))
def testLocal(self): barFeed = googlefeed.Feed() instrument = "orcl" barFeed.addBarsFromCSV( instrument, common.get_data_file_path("orcl-2000-googlefinance.csv")) res = local.run(sma_crossover.SMACrossOver, barFeed, parameters_generator(instrument, 5, 100), logLevel=logging.DEBUG) self.assertEquals(round(res.getResult(), 2), 1295462.6) self.assertEquals(res.getParameters()[1], 20)
def testNoTrades(self): barFeed = googlefeed.Feed() barFeed.addBarsFromCSV( "ige", common.get_data_file_path("sharpe-ratio-test-ige.csv")) strat = strategy_test.TestStrategy(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)
def testBaseFeedInterface(self): tmpFeed = TemporarySQLiteFeed(SQLiteFeedTestCase.dbName, bar.Frequency.DAY) with tmpFeed: # Load bars using a Google feed. googleFeed = googlefeed.Feed() googleFeed.addBarsFromCSV("orcl", common.get_data_file_path("orcl-2000-googlefinance.csv"), marketsession.USEquities.timezone) googleFeed.addBarsFromCSV("orcl", common.get_data_file_path("orcl-2001-googlefinance.csv"), marketsession.USEquities.timezone) # Fill the database using the bars from the Google feed. sqliteFeed = tmpFeed.getFeed() sqliteFeed.getDatabase().addBarsFromFeed(googleFeed) # Load the SQLite feed and process all bars. sqliteFeed.loadBars("orcl") feed_test.tstBaseFeedInterface(self, sqliteFeed)
def testDifferentTimezones(self): # Market times in UTC: # - TSE: 0hs ~ 6hs # - US: 14:30hs ~ 21hs feed = googlefeed.Feed() for year in [2010, 2011]: feed.addBarsFromCSV( "^n225", common.get_data_file_path( "nikkei-%d-googlefinance.csv" % year), marketsession.TSE.getTimezone()) feed.addBarsFromCSV( "spy", common.get_data_file_path("spy-%d-googlefinance.csv" % year), marketsession.USEquities.getTimezone()) self.__testDifferentTimezonesImpl(feed)
def testNoTrades(self): barFeed = googlefeed.Feed() barFeed.addBarsFromCSV( "ige", common.get_data_file_path("sharpe-ratio-test-ige.csv")) barFeed.addBarsFromCSV( "spy", common.get_data_file_path("sharpe-ratio-test-spy.csv")) strat = strategy_test.TestStrategy(barFeed, 1000) strat.setBrokerOrdersGTC(True) strat.setUseAdjustedValues(True) stratAnalyzer = drawdown.DrawDown() strat.attachAnalyzer(stratAnalyzer) strat.run() self.assertTrue(strat.getBroker().getCash() == 1000) self.assertEqual(strat.orderUpdatedCalls, 0) self.assertTrue(stratAnalyzer.getMaxDrawDown() == 0) self.assertTrue( stratAnalyzer.getLongestDrawDownDuration() == datetime.timedelta())
def main(): # Load the orders file. ordersFile = OrdersFile("orders.csv") print "First date", ordersFile.getFirstDate() print "Last date", ordersFile.getLastDate() print "Symbols", ordersFile.getInstruments() # Load the data from QSTK storage. QS environment variable has to be defined. if os.getenv("QS") is None: raise Exception("QS environment variable not defined") feed = googlefeed.Feed() feed.setBarFilter( csvfeed.DateRangeFilter(ordersFile.getFirstDate(), ordersFile.getLastDate())) feed.setDailyBarTime( datetime.time(0, 0, 0) ) # This is to match the dates loaded with the ones in the orders file. for symbol in ordersFile.getInstruments(): feed.addBarsFromCSV( symbol, os.path.join(os.getenv("QS"), "QSData", "Yahoo", symbol + ".csv")) # Run the strategy. cash = 1000000 useAdjustedClose = True myStrategy = MyStrategy(feed, cash, ordersFile, useAdjustedClose) # Attach returns and sharpe ratio analyzers. retAnalyzer = returns.Returns() myStrategy.attachAnalyzer(retAnalyzer) sharpeRatioAnalyzer = sharpe.SharpeRatio() myStrategy.attachAnalyzer(sharpeRatioAnalyzer) 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))
def testMultipleInstrumentsInterleaved(self): barFeed = googlefeed.Feed() barFeed.addBarsFromCSV( "spy", common.get_data_file_path("spy-2010-googlefinance.csv"), marketsession.NYSE.getTimezone()) barFeed.addBarsFromCSV( "nikkei", common.get_data_file_path("nikkei-2010-googlefinance.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 = googlefeed.Feed() barFeed.addBarsFromCSV( AnalyzerTestCase.TestInstrument, common.get_data_file_path("goog-2011-googlefinance.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))
def testEventsOnBoundary(self): feed = googlefeed.Feed() feed.addBarsFromCSV( "orcl", common.get_data_file_path("orcl-2000-googlefinance.csv")) dates = [] dates.append(datetime.date(2000, 1, 3)) dates.append(datetime.date(2000, 1, 4)) dates.append(datetime.date(2000, 1, 5)) dates.append(datetime.date(2000, 1, 6)) dates.append(datetime.date(2000, 1, 7)) dates.append(datetime.date(2000, 1, 10)) dates.append(datetime.date(2000, 12, 22)) dates.append(datetime.date(2000, 12, 26)) dates.append(datetime.date(2000, 12, 27)) dates.append(datetime.date(2000, 12, 28)) dates.append(datetime.date(2000, 12, 29)) predicate = Predicate(dates) eventProfiler = eventprofiler.Profiler(predicate, 5, 5) eventProfiler.run(feed, True) self.assertEqual(eventProfiler.getResults().getEventCount(), 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 = googlefeed.Feed() barFeed.addBarsFromCSV( "ige", common.get_data_file_path("sharpe-ratio-test-ige.csv")) strat = strategy_test.TestStrategy(barFeed, initialCash) strat.setUseAdjustedValues(True) strat.setBrokerOrdersGTC(True) stratAnalyzer = drawdown.DrawDown() 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.assertTrue( round(strat.getBroker().getCash(), 2) == initialCash + (127.64 - 42.09) * quantity) self.assertEqual(strat.orderUpdatedCalls, 6) self.assertTrue(round(stratAnalyzer.getMaxDrawDown(), 5) == 0.31178) self.assertTrue( stratAnalyzer.getLongestDrawDownDuration() == datetime.timedelta( days=623))