def testBounded(self): tmpFeed = TemporarySQLiteFeed(SQLiteFeedTestCase.dbName, bar.Frequency.DAY, maxLen=2) with tmpFeed: # Load bars using a Yahoo! feed. yahooFeed = yahoofeed.Feed(maxLen=1) yahooFeed.addBarsFromCSV("orcl", common.get_data_file_path("orcl-2000-yahoofinance.csv"), marketsession.USEquities.timezone) yahooFeed.addBarsFromCSV("orcl", common.get_data_file_path("orcl-2001-yahoofinance.csv"), marketsession.USEquities.timezone) # Fill the database using the bars from the Yahoo! feed. sqliteFeed = tmpFeed.getFeed() sqliteFeed.getDatabase().addBarsFromFeed(yahooFeed) # 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 testSharpeRatioIGE_SPY_Broker(self): initialCash = 42.09 # This testcase is based on an example from Ernie Chan's book: # 'Quantitative Trading: How to Build Your Own Algorithmic Trading Business' bar_feed = yahoofeed.Feed() bar_feed.add_bars_from_csv("ige", common.get_data_file_path("sharpe-ratio-test-ige.csv")) bar_feed.add_bars_from_csv("spy", common.get_data_file_path("sharpe-ratio-test-spy.csv")) strat = strategy_test.TestStrategy(bar_feed, initialCash) strat.get_broker().set_use_adj_values(True) strat.setBrokerOrdersGTC(True) stratAnalyzer = sharpe.SharpeRatio() strat.attach_analyzer(stratAnalyzer) # Manually place IGE order to get it filled on the first bar. order = strat.get_broker().create_market_order(broker.Order.Action.BUY, "ige", 1, True) # Adj. Close: 42.09 order.set_good_until_canceled(True) strat.get_broker().place_order(order) # Manually place SPY order to get it filled on the first bar. order = strat.get_broker().create_market_order(broker.Order.Action.SELL_SHORT, "spy", 1, True) # Adj. Close: 105.52 order.set_good_until_canceled(True) strat.get_broker().place_order(order) strat.addOrder(strategy_test.datetime_from_date(2007, 11, 13), strat.get_broker().create_market_order, broker.Order.Action.SELL, "ige", 1, True) # Adj. Close: 127.64 strat.addOrder(strategy_test.datetime_from_date(2007, 11, 13), strat.get_broker().create_market_order, broker.Order.Action.BUY_TO_COVER, "spy", 1, True) # Adj. Close: 147.67 strat.run() self.assertTrue(strat.get_order_updated_events() == 4) self.assertTrue(round(strat.get_broker().get_cash(), 2) == round(initialCash + (127.64 - 42.09) + (105.52 - 147.67), 2))
def testDrawDownIGE_SPY_Broker(self): # 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")) barFeed.addBarsFromCSV("spy", common.get_data_file_path("sharpe-ratio-test-spy.csv")) strat = strategy_test.TestStrategy(barFeed, 1000) strat.getBroker().setUseAdjustedValues(True) strat.setBrokerOrdersGTC(True) stratAnalyzer = drawdown.DrawDown() strat.attachAnalyzer(stratAnalyzer) # Manually place IGE order to get it filled on the first bar. order = strat.getBroker().createMarketOrder(broker.Order.Action.BUY, "ige", 1, True) # Adj. Close: 42.09 order.setGoodTillCanceled(True) strat.getBroker().placeOrder(order) strat.addOrder(strategy_test.datetime_from_date(2007, 11, 13), strat.getBroker().createMarketOrder, broker.Order.Action.SELL, "ige", 1, True) # Adj. Close: 127.64 # Manually place SPY order to get it filled on the first bar. order = strat.getBroker().createMarketOrder(broker.Order.Action.SELL_SHORT, "spy", 1, True) # Adj. Close: 105.52 order.setGoodTillCanceled(True) strat.getBroker().placeOrder(order) strat.addOrder(strategy_test.datetime_from_date(2007, 11, 13), strat.getBroker().createMarketOrder, broker.Order.Action.BUY_TO_COVER, "spy", 1, True) # Adj. Close: 147.67 strat.run() self.assertTrue(round(strat.getBroker().getCash(), 2) == round(1000 + (127.64 - 42.09) + (105.52 - 147.67), 2)) self.assertTrue(strat.getOrderUpdatedEvents() == 4) self.assertTrue(round(stratAnalyzer.getMaxDrawDown(), 5) == 0.09448) self.assertTrue(stratAnalyzer.getMaxDrawDownDuration()== 229)
def testWithPerFileTimezone(self): barFeed = yahoofeed.Feed() barFeed.addBarsFromCSV(FeedTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv"), marketsession.USEquities.getTimezone()) barFeed.addBarsFromCSV(FeedTestCase.TestInstrument, common.get_data_file_path("orcl-2001-yahoofinance.csv"), marketsession.USEquities.getTimezone()) for dateTime, bars in barFeed: bar = bars.getBar(FeedTestCase.TestInstrument) self.assertFalse(dt.datetime_is_naive(bar.getDateTime()))
def testWithoutTimezone(self): barFeed = yahoofeed.Feed() barFeed.addBarsFromCSV(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv")) barFeed.addBarsFromCSV(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2001-yahoofinance.csv")) for dateTime, bars in barFeed: bar = bars.getBar(YahooTestCase.TestInstrument) self.assertTrue(dt.datetime_is_naive(bar.getDateTime()))
def testLoadDailyBars(self): tmpFeed = TemporarySQLiteFeed(SQLiteFeedTestCase.dbName, barfeed.Frequency.DAY) with tmpFeed: # Load bars using a Yahoo! feed. yahooFeed = yahoofeed.Feed() yahooFeed.addBarsFromCSV("orcl", common.get_data_file_path("orcl-2000-yahoofinance.csv"), marketsession.USEquities.timezone) yahooFeed.addBarsFromCSV("orcl", common.get_data_file_path("orcl-2001-yahoofinance.csv"), marketsession.USEquities.timezone) # Fill the database using the bars from the Yahoo! feed. sqliteFeed = tmpFeed.getFeed() sqliteFeed.getDatabase().addBarsFromFeed(yahooFeed) # Load the SQLite feed and process all bars. sqliteFeed.loadBars("orcl") sqliteFeed.start() for bars in sqliteFeed: pass sqliteFeed.stop() sqliteFeed.join() # Check that both dataseries have the same bars. yahooDS = yahooFeed["orcl"] sqliteDS = sqliteFeed["orcl"] self.assertEqual(len(yahooDS), len(sqliteDS)) for i in xrange(len(yahooDS)): self.assertEqual(yahooDS[i].getDateTime(), sqliteDS[i].getDateTime()) self.assertEqual(yahooDS[i].getOpen(), sqliteDS[i].getOpen()) self.assertEqual(yahooDS[i].getHigh(), sqliteDS[i].getHigh()) self.assertEqual(yahooDS[i].getLow(), sqliteDS[i].getLow()) self.assertEqual(yahooDS[i].getClose(), sqliteDS[i].getClose()) self.assertEqual(yahooDS[i].getAdjClose(), sqliteDS[i].getAdjClose()) self.assertEqual(yahooDS[i].getBarsTillSessionClose(), sqliteDS[i].getBarsTillSessionClose()) self.assertEqual(yahooDS[i].getSessionClose(), sqliteDS[i].getSessionClose())
def testWithPerFileTimezone(self): bar_feed = yahoofeed.Feed() bar_feed.add_bars_from_csv(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv"), marketsession.USEquities.getTimezone()) bar_feed.add_bars_from_csv(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2001-yahoofinance.csv"), marketsession.USEquities.getTimezone()) bar_feed.start() for bars in bar_feed: bar = bars.get_bar(YahooTestCase.TestInstrument) self.assertFalse(dt.datetime_is_naive(bar.get_date_time())) bar_feed.stop() bar_feed.join()
def testWithDefaultTimezone(self): barFeed = yahoofeed.Feed(marketsession.USEquities.getTimezone()) barFeed.addBarsFromCSV(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv")) barFeed.addBarsFromCSV(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2001-yahoofinance.csv")) barFeed.start() for bars in barFeed: bar = bars.getBar(YahooTestCase.TestInstrument) self.assertFalse(dt.datetime_is_naive(bar.getDateTime())) barFeed.stop() barFeed.join()
def testDifferentTimezones(self): # Market times in UTC: # - TSE: 0hs ~ 6hs # - US: 14:30hs ~ 21hs feed = yahoofeed.Feed() for year in [2010, 2011]: feed.add_bars_from_csv("^n225", common.get_data_file_path("nikkei-%d-yahoofinance.csv" % year), marketsession.TSE.getTimezone()) feed.add_bars_from_csv("spy", common.get_data_file_path("spy-%d-yahoofinance.csv" % year), marketsession.USEquities.getTimezone()) self.__testDifferentTimezonesImpl(feed)
def __testFilteredRangeImpl(self, fromDate, toDate, year): barFeed = csvfeed.YahooFeed() barFeed.setBarFilter(csvfeed.DateRangeFilter(fromDate, toDate)) barFeed.addBarsFromCSV(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv")) barFeed.addBarsFromCSV(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2001-yahoofinance.csv")) count = 0 for bars in barFeed: count += 1 self.assertTrue(bars.getBar(YahooTestCase.TestInstrument).getDateTime().year == year) self.assertTrue(count > 0)
def testCSVFeedLoadOrder(self): barFeed = ibfeed.CSVFeed() barFeed.addBarsFromCSV(IBTestCase.TestInstrument, common.get_data_file_path("ib-spy-5min-20120627.csv")) barFeed.addBarsFromCSV(IBTestCase.TestInstrument, common.get_data_file_path("ib-spy-5min-20120628.csv")) barFeed.addBarsFromCSV(IBTestCase.TestInstrument, common.get_data_file_path("ib-spy-5min-20120629.csv")) handler = BarFeedEventHandler_TestLoadOrder(self, barFeed, IBTestCase.TestInstrument) barFeed.getNewBarsEvent().subscribe(handler.onBars) while not barFeed.stopDispatching(): barFeed.dispatch() self.assertTrue(handler.getEventCount() > 0)
def testCSVFeedLoadOrder(self): barFeed = yahoofeed.Feed() barFeed.addBarsFromCSV(FeedTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv")) barFeed.addBarsFromCSV(FeedTestCase.TestInstrument, common.get_data_file_path("orcl-2001-yahoofinance.csv")) # Dispatch and handle events. handler = BarFeedEventHandler_TestLoadOrder(self, barFeed, FeedTestCase.TestInstrument) barFeed.getNewBarsEvent().subscribe(handler.onBars) while not barFeed.eof(): barFeed.dispatch() self.assertTrue(handler.getEventCount() > 0)
def testCSVFeedLoadOrder(self): bar_feed = csvfeed.YahooFeed() bar_feed.add_bars_from_csv(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv")) bar_feed.add_bars_from_csv(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2001-yahoofinance.csv")) # Dispatch and handle events. handler = BarFeedEventHandler_TestLoadOrder(self, bar_feed, YahooTestCase.TestInstrument) bar_feed.get_new_bars_event().subscribe(handler.on_bars) while not bar_feed.stop_dispatching(): bar_feed.dispatch() self.assertTrue(handler.get_eventCount() > 0)
def __testFilteredRangeImpl(self, fromDate, toDate): barFeed = yahoofeed.Feed() barFeed.setBarFilter(csvfeed.DateRangeFilter(fromDate, toDate)) barFeed.addBarsFromCSV(FeedTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv")) barFeed.addBarsFromCSV(FeedTestCase.TestInstrument, common.get_data_file_path("orcl-2001-yahoofinance.csv")) # Dispatch and handle events. handler = BarFeedEventHandler_TestFilterRange(self, FeedTestCase.TestInstrument, fromDate, toDate) barFeed.getNewBarsEvent().subscribe(handler.onBars) while not barFeed.eof(): barFeed.dispatch() self.assertTrue(handler.getEventCount() > 0)
def __testFilteredRangeImpl(self, from_date, toDate): bar_feed = csvfeed.YahooFeed() bar_feed.set_bar_filter(csvfeed.DateRangeFilter(from_date, toDate)) bar_feed.add_bars_from_csv(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv")) bar_feed.add_bars_from_csv(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2001-yahoofinance.csv")) # Dispatch and handle events. handler = BarFeedEventHandler_TestFilterRange(self, YahooTestCase.TestInstrument, from_date, toDate) bar_feed.get_new_bars_event().subscribe(handler.on_bars) while not bar_feed.stop_dispatching(): bar_feed.dispatch() self.assertTrue(handler.get_eventCount() > 0)
def testDifferentTimezones(self): # Market times in UTC: # - TSE: 0hs ~ 6hs # - US: 14:30hs ~ 21hs feed = yahoofeed.Feed() for year in [2010, 2011]: feed.addBarsFromCSV("nikkei", common.get_data_file_path("nikkei-%d-yahoofinance.csv" % year), marketsession.TSE.getTimezone()) feed.addBarsFromCSV("spy", common.get_data_file_path("spy-%d-yahoofinance.csv" % year), marketsession.USEquities.getTimezone()) strat = NikkeiSpyStrategy(feed, 34) strat.run() assert(round(strat.getResult(), 2) == 1125558.12)
def testDefaultTimezoneIsUTC(self): barFeed = yahoofeed.Feed() barFeed.addBarsFromCSV(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv"), timezone=None) barFeed.addBarsFromCSV(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2001-yahoofinance.csv"), timezone=None) barFeed.start() for bars in barFeed: bar = bars.getBar(YahooTestCase.TestInstrument) assert bar.getDateTime().tzinfo == pytz.utc barFeed.stop() barFeed.join()
def __testFilteredRangeImpl(self, fromDate, toDate): barFeed = ibfeed.CSVFeed() barFeed.setBarFilter(csvfeed.DateRangeFilter(fromDate, toDate)) barFeed.addBarsFromCSV(IBTestCase.TestInstrument, common.get_data_file_path("ib-spy-5min-20120627.csv")) barFeed.addBarsFromCSV(IBTestCase.TestInstrument, common.get_data_file_path("ib-spy-5min-20120628.csv")) barFeed.addBarsFromCSV(IBTestCase.TestInstrument, common.get_data_file_path("ib-spy-5min-20120629.csv")) # Dispatch and handle events. handler = BarFeedEventHandler_TestFilterRange(self, IBTestCase.TestInstrument, fromDate, toDate) barFeed.getNewBarsEvent().subscribe(handler.onBars) while not barFeed.stopDispatching(): barFeed.dispatch() self.assertTrue(handler.getEventCount() > 0)
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 testWithoutTimezone(self): # At the moment we need to set both the Feed's constructor and addBarsFromCSV to None in order to get a naive # datetime barFeed = yahoofeed.Feed(timezone=None) barFeed.addBarsFromCSV(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv"), timezone=None) barFeed.addBarsFromCSV(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2001-yahoofinance.csv"), timezone=None) barFeed.start() for bars in barFeed: bar = bars.getBar(YahooTestCase.TestInstrument) assert dt.datetime_is_naive(bar.getDateTime()) barFeed.stop() barFeed.join()
def testBaseFeedInterface(self): tmpFeed = TemporarySQLiteFeed(SQLiteFeedTestCase.dbName, bar.Frequency.DAY) with tmpFeed: # Load bars using a Yahoo! feed. yahooFeed = yahoofeed.Feed() yahooFeed.addBarsFromCSV("orcl", common.get_data_file_path("orcl-2000-yahoofinance.csv"), marketsession.USEquities.timezone) yahooFeed.addBarsFromCSV("orcl", common.get_data_file_path("orcl-2001-yahoofinance.csv"), marketsession.USEquities.timezone) # Fill the database using the bars from the Yahoo! feed. sqliteFeed = tmpFeed.getFeed() sqliteFeed.getDatabase().addBarsFromFeed(yahooFeed) # Load the SQLite feed and process all bars. sqliteFeed.loadBars("orcl") feed_test.tstBaseFeedInterface(self, sqliteFeed)
def testNoTrades(self): bar_feed = yahoofeed.Feed() bar_feed.add_bars_from_csv("ige", common.get_data_file_path("sharpe-ratio-test-ige.csv")) bar_feed.add_bars_from_csv("spy", common.get_data_file_path("sharpe-ratio-test-spy.csv")) strat = strategy_test.TestStrategy(bar_feed, 1000) strat.setBrokerOrdersGTC(True) strat.get_broker().set_use_adj_values(True) stratAnalyzer = drawdown.DrawDown() strat.attach_analyzer(stratAnalyzer) strat.run() self.assertTrue(strat.get_broker().get_cash() == 1000) self.assertTrue(strat.get_order_updated_events() == 0) self.assertTrue(stratAnalyzer.get_max_draw_down() == 0) self.assertTrue(stratAnalyzer.get_longest_draw_down_duration()== 0)
def testNoTrades(self): barFeed = yahoofeed.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 testDownloadAndParseDaily(self): instrument = "orcl" barFeed = yahoofeed.Feed() barFeed.addBarsFromCSV(instrument, common.get_data_file_path("orcl-2000-yahoofinance.csv")) strat = sma_crossover.SMACrossOver(barFeed, instrument, 20) plt = plotter.StrategyPlotter(strat, True, True, True) plt.getInstrumentSubplot(instrument).addDataSeries("sma", strat.getSMA()) strat.run() with common.TmpDir() as tmpPath: fig = plt.buildFigure() fig.set_size_inches(10, 8) png = os.path.join(tmpPath, "plotter_test.png") fig.savefig(png) self.assertEquals(open(common.get_data_file_path("plotter_test.png"), "r").read(), open(png, "r").read())
def testNoTrades(self): barFeed = yahoofeed.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.DummyStrategy(barFeed, 1000) strat.setBrokerOrdersGTC(True) strat.getBroker().setUseAdjustedValues(True) stratAnalyzer = drawdown.DrawDown() strat.attachAnalyzer(stratAnalyzer) strat.run() assert strat.getBroker().getCash() == 1000 assert strat.getOrderUpdatedEvents() == 0 assert stratAnalyzer.getMaxDrawDown() == 0 assert stratAnalyzer.getLongestDrawDownDuration()== 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.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().placeOrder(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, 4) self.assertTrue(round(stratAnalyzer.getMaxDrawDown(), 5) == 0.31178) self.assertTrue(stratAnalyzer.getLongestDrawDownDuration() == datetime.timedelta(days=623))
def __test(self, strategyClass, finalValue): feed = yahoofeed.Feed() feed.addBarsFromCSV("orcl", common.get_data_file_path("orcl-2001-yahoofinance.csv")) myStrategy = strategyClass(feed, 10, 25) myStrategy.run() myStrategy.printDebug("Final result:", round(myStrategy.getFinalValue(), 2)) self.assertTrue(round(myStrategy.getFinalValue(), 2) == finalValue)
def testResampleNinjaTraderHour(self): # Resample. feed = ninjatraderfeed.Feed(ninjatraderfeed.Frequency.MINUTE) feed.addBarsFromCSV("spy", common.get_data_file_path("nt-spy-minute-2011.csv")) resampledBarDS = resampled.ResampledBarDataSeries(feed["spy"], barfeed.Frequency.HOUR) resampledFile = os.path.join(common.get_temp_path(), "hour-nt-spy-minute-2011.csv") resample.resample_to_csv(feed, barfeed.Frequency.HOUR, resampledFile) resampledBarDS.pushLast() # Need to manually push the last stot since time didn't change. # Load the resampled file. feed = csvfeed.GenericBarFeed(barfeed.Frequency.HOUR, marketsession.USEquities.getTimezone()) feed.addBarsFromCSV("spy", resampledFile) feed.loadAll() self.assertEqual(len(feed["spy"]), 340) self.assertEqual(feed["spy"][0].getDateTime(), dt.localize(datetime.datetime(2011, 1, 3, 9), marketsession.USEquities.getTimezone())) self.assertEqual(feed["spy"][-1].getDateTime(), dt.localize(datetime.datetime(2011, 2, 1, 1), marketsession.USEquities.getTimezone())) self.assertEqual(feed["spy"][0].getOpen(), 126.35) self.assertEqual(feed["spy"][0].getHigh(), 126.45) self.assertEqual(feed["spy"][0].getLow(), 126.3) self.assertEqual(feed["spy"][0].getClose(), 126.4) self.assertEqual(feed["spy"][0].getVolume(), 3397.0) self.assertEqual(feed["spy"][0].getAdjClose(), None) self.assertEqual(len(resampledBarDS), len(feed["spy"])) self.assertEqual(resampledBarDS[0].getDateTime(), dt.as_utc(datetime.datetime(2011, 1, 3, 9))) self.assertEqual(resampledBarDS[-1].getDateTime(), dt.as_utc(datetime.datetime(2011, 2, 1, 1)))
def testIGE_BrokerWithCommission(self): commision = 0.5 initialCash = 42.09 + commision # 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.TestStrategy(barFeed, initialCash) strat.getBroker().setCommission(backtesting.FixedPerTrade(commision)) 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", 1, True) # Adj. Close: 42.09 order.setGoodTillCanceled(True) strat.getBroker().placeOrder(order) strat.addOrder(strategy_test.datetime_from_date(2007, 11, 13), strat.getBroker().createMarketOrder, broker.Order.Action.SELL, "ige", 1, True) # Adj. Close: 127.64 strat.run() self.assertTrue(round(strat.getBroker().getCash(), 2) == initialCash + (127.64 - 42.09 - commision*2)) self.assertTrue(strat.getOrderUpdatedEvents() == 4) # The results are slightly different only because I'm taking into account the first bar as well, # and I'm also adding commissions. self.assertEqual(round(stratAnalyzer.getSharpeRatio(0.04, True), 6), 0.776443)
def testResampleMtGoxDay(self): # Resample. feed = mtgoxfeed.CSVTradeFeed() feed.addBarsFromCSV(common.get_data_file_path("trades-mgtox-usd-2013-01-01.csv")) resampledBarDS = resampled.ResampledBarDataSeries(feed["BTC"], barfeed.Frequency.DAY) resampledFile = os.path.join(common.get_temp_path(), "day-mgtox-usd-2013-01-01.csv") resample.resample_to_csv(feed, barfeed.Frequency.DAY, resampledFile) resampledBarDS.pushLast() # Need to manually push the last stot since time didn't change. # Load the resampled file. feed = csvfeed.GenericBarFeed(barfeed.Frequency.DAY) feed.addBarsFromCSV("BTC", resampledFile) feed.loadAll() self.assertEqual(len(feed["BTC"]), 1) self.assertEqual(feed["BTC"][0].getDateTime(), datetime.datetime(2013, 1, 1)) self.assertEqual(feed["BTC"][0].getOpen(), 13.51001) self.assertEqual(feed["BTC"][0].getHigh(), 13.56) self.assertEqual(feed["BTC"][0].getLow(), 13.16123) self.assertEqual(feed["BTC"][0].getClose(), 13.30413) self.assertEqual(feed["BTC"][0].getVolume(), 28168.9114596) self.assertEqual(feed["BTC"][0].getAdjClose(), 13.30413) self.assertEqual(len(resampledBarDS), len(feed["BTC"])) self.assertEqual(resampledBarDS[0].getDateTime(), dt.as_utc(feed["BTC"][0].getDateTime())) self.assertEqual(resampledBarDS[-1].getDateTime(), dt.as_utc(feed["BTC"][-1].getDateTime())) self.assertEqual(resampledBarDS[0].getOpen(), feed["BTC"][0].getOpen()) self.assertEqual(resampledBarDS[0].getHigh(), feed["BTC"][0].getHigh()) self.assertEqual(resampledBarDS[0].getLow(), feed["BTC"][0].getLow()) self.assertEqual(resampledBarDS[0].getClose(), feed["BTC"][0].getClose()) self.assertEqual(round(resampledBarDS[0].getVolume(), 5), round(feed["BTC"][0].getVolume(), 5)) self.assertEqual(resampledBarDS[0].getAdjClose(), feed["BTC"][0].getAdjClose())
def testNoTrades(self): barFeed = yahoofeed.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.getBroker().setUseAdjustedValues(True) stratAnalyzer = drawdown.DrawDown() strat.attachAnalyzer(stratAnalyzer) strat.run() self.assertTrue(strat.getBroker().getCash() == 1000) self.assertTrue(strat.getOrderUpdatedEvents() == 0) self.assertTrue(stratAnalyzer.getMaxDrawDown() == 0) self.assertTrue(stratAnalyzer.getMaxDrawDownDuration() == 0)
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 testDefaultInstrument(self): barFeed = yahoofeed.Feed() self.assertEquals(barFeed.getDefaultInstrument(), None) barFeed.addBarsFromCSV( FeedTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv")) self.assertEquals(barFeed.getDefaultInstrument(), FeedTestCase.TestInstrument)
def __testFilteredRangeImpl(self, fromDate, toDate): barFeed = yahoofeed.Feed() barFeed.setBarFilter(csvfeed.DateRangeFilter(fromDate, toDate)) barFeed.addBarsFromCSV( FeedTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv")) barFeed.addBarsFromCSV( FeedTestCase.TestInstrument, common.get_data_file_path("orcl-2001-yahoofinance.csv")) # Dispatch and handle events. handler = BarFeedEventHandler_TestFilterRange( self, FeedTestCase.TestInstrument, fromDate, toDate) barFeed.getNewValuesEvent().subscribe(handler.onBars) while not barFeed.eof(): barFeed.dispatch() self.assertTrue(handler.getEventCount() > 0)
def __createStrategy(self): bar_feed = ninjatraderfeed.Feed(ninjatraderfeed.Frequency.MINUTE) bar_filter = csvfeed.USEquitiesRTH() bar_feed.set_bar_filter(bar_filter) bar_feed.add_bars_from_csv( TradesAnalyzerTestCase.TestInstrument, common.get_data_file_path("nt-spy-minute-2011.csv")) return strategy_test.TestStrategy(bar_feed, 1000)
def testLoadDailyBars(self): tmpFeed = TemporarySQLiteFeed(SQLiteFeedTestCase.dbName, bar.Frequency.DAY) with tmpFeed: # Load bars using a Yahoo! feed. yahooFeed = yahoofeed.Feed() yahooFeed.add_bars_from_csv( "orcl", common.get_data_file_path("orcl-2000-yahoofinance.csv"), marketsession.USEquities.timezone) yahooFeed.add_bars_from_csv( "orcl", common.get_data_file_path("orcl-2001-yahoofinance.csv"), marketsession.USEquities.timezone) # Fill the database using the bars from the Yahoo! feed. sqliteFeed = tmpFeed.get_feed() sqliteFeed.get_database().add_bars_from_feed(yahooFeed) # Load the SQLite feed and process all bars. sqliteFeed.load_bars("orcl") sqliteFeed.start() for bars in sqliteFeed: pass sqliteFeed.stop() sqliteFeed.join() # Check that both dataseries have the same bars. yahooDS = yahooFeed["orcl"] sqliteDS = sqliteFeed["orcl"] self.assertEqual(len(yahooDS), len(sqliteDS)) for i in xrange(len(yahooDS)): self.assertEqual(yahooDS[i].get_date_time(), sqliteDS[i].get_date_time()) self.assertEqual(yahooDS[i].get_open(), sqliteDS[i].get_open()) self.assertEqual(yahooDS[i].get_high(), sqliteDS[i].get_high()) self.assertEqual(yahooDS[i].get_low(), sqliteDS[i].get_low()) self.assertEqual(yahooDS[i].get_close(), sqliteDS[i].get_close()) self.assertEqual(yahooDS[i].get_adj_close(), sqliteDS[i].get_adj_close()) self.assertEqual(yahooDS[i].get_bars_until_session_close(), sqliteDS[i].get_bars_until_session_close()) self.assertEqual(yahooDS[i].get_session_close(), sqliteDS[i].get_session_close())
def testLocal(self): barFeed = yahoofeed.Feed() instrument = "orcl" barFeed.addBarsFromCSV(instrument, common.get_data_file_path("orcl-2000-yahoofinance.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 testMapTypeOperations(self): barFeed = yahoofeed.Feed() barFeed.addBarsFromCSV(FeedTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv"), marketsession.USEquities.getTimezone()) for dateTime, bars in barFeed: self.assertTrue(FeedTestCase.TestInstrument in bars) self.assertFalse(FeedTestCase.TestInstrument not in bars) bars[FeedTestCase.TestInstrument] with self.assertRaises(KeyError): bars["pirulo"]
def __loadIntradayBarFeed(self): ret = ninjatraderfeed.Feed(ninjatraderfeed.Frequency.MINUTE) ret.addBarsFromCSV("spy", common.get_data_file_path("nt-spy-minute-2011.csv")) # This is need to get session close attributes set. Strategy class is responsible for calling this. ret.start() # Process all events to get the dataseries fully loaded. while not ret.stopDispatching(): ret.dispatch() return ret
def __test(self, strategy_class, finalValue): feed = yahoofeed.Feed() feed.add_bars_from_csv( "orcl", common.get_data_file_path("orcl-2001-yahoofinance.csv")) myStrategy = strategy_class(feed, 10, 25) myStrategy.run() myStrategy.printDebug("Final result:", round(myStrategy.getFinalValue(), 2)) self.assertTrue(round(myStrategy.getFinalValue(), 2) == finalValue)
def testFailingStrategy(self): barFeed = yahoofeed.Feed() instrument = "orcl" barFeed.addBarsFromCSV( instrument, common.get_data_file_path("orcl-2000-yahoofinance.csv")) res = local.run(FailingStrategy, barFeed, parameters_generator(instrument, 5, 100)) self.assertIsNone(res)
def testNoEvents(self): feed = yahoofeed.Feed() feed.addBarsFromCSV( "orcl", common.get_data_file_path("orcl-2000-yahoofinance.csv")) predicate = Predicate([]) eventProfiler = eventprofiler.Profiler(predicate, 5, 5) eventProfiler.run(feed, True) self.assertEqual(eventProfiler.getResults().getEventCount(), 0)
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 testDrawDownIGE_SPY_Broker(self): # 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")) barFeed.addBarsFromCSV( "spy", common.get_data_file_path("sharpe-ratio-test-spy.csv")) strat = strategy_test.TestStrategy(barFeed, 1000) strat.getBroker().setUseAdjustedValues(True) strat.setBrokerOrdersGTC(True) stratAnalyzer = drawdown.DrawDown() strat.attachAnalyzer(stratAnalyzer) # Manually place IGE order to get it filled on the first bar. order = strat.getBroker().createMarketOrder(broker.Order.Action.BUY, "ige", 1, True) # Adj. Close: 42.09 order.setGoodTillCanceled(True) strat.getBroker().placeOrder(order) strat.addOrder(strategy_test.datetime_from_date(2007, 11, 13), strat.getBroker().createMarketOrder, broker.Order.Action.SELL, "ige", 1, True) # Adj. Close: 127.64 # Manually place SPY order to get it filled on the first bar. order = strat.getBroker().createMarketOrder( broker.Order.Action.SELL_SHORT, "spy", 1, True) # Adj. Close: 105.52 order.setGoodTillCanceled(True) strat.getBroker().placeOrder(order) strat.addOrder(strategy_test.datetime_from_date(2007, 11, 13), strat.getBroker().createMarketOrder, broker.Order.Action.BUY_TO_COVER, "spy", 1, True) # Adj. Close: 147.67 strat.run() self.assertTrue( round(strat.getBroker().getCash(), 2) == round( 1000 + (127.64 - 42.09) + (105.52 - 147.67), 2)) self.assertTrue(strat.getOrderUpdatedEvents() == 4) self.assertTrue(round(stratAnalyzer.getMaxDrawDown(), 5) == 0.09448) self.assertTrue(stratAnalyzer.getMaxDrawDownDuration() == 229)
def testMaxRecursion(self): barFeed = ninjatraderfeed.Feed(bar.Frequency.MINUTE) barFeed.addBarsFromCSV( "any", common.get_data_file_path("nt-spy-minute-2011.csv")) ema = ma.EMA(barFeed["any"].getPriceDataSeries(), 10) # Load all the feed. barFeed.loadAll() # Check that the max recursion limit bug is not hit when generating the last value first. self.assertEqual(round(ema[-1], 2), 128.81)
def loadIntradayBarFeed(self): fromMonth = 1 toMonth = 1 fromDay = 3 toDay = 3 barFilter = csvfeed.USEquitiesRTH(us_equities_datetime(2011, fromMonth, fromDay, 00, 00), us_equities_datetime(2011, toMonth, toDay, 23, 59)) barFeed = ninjatraderfeed.Feed(barfeed.Frequency.MINUTE) barFeed.setBarFilter(barFilter) barFeed.addBarsFromCSV(BaseTestCase.TestInstrument, common.get_data_file_path("nt-spy-minute-2011.csv")) return barFeed
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.order("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 testSharpeRatioIGE_SPY_Broker(self): initialCash = 42.09 # This testcase is based on an example from Ernie Chan's book: # 'Quantitative Trading: How to Build Your Own Algorithmic Trading Business' bar_feed = yahoofeed.Feed() bar_feed.add_bars_from_csv( "ige", common.get_data_file_path("sharpe-ratio-test-ige.csv")) bar_feed.add_bars_from_csv( "spy", common.get_data_file_path("sharpe-ratio-test-spy.csv")) strat = strategy_test.TestStrategy(bar_feed, initialCash) strat.get_broker().set_use_adj_values(True) strat.setBrokerOrdersGTC(True) stratAnalyzer = sharpe.SharpeRatio() strat.attach_analyzer(stratAnalyzer) # Manually place IGE order to get it filled on the first bar. order = strat.get_broker().create_market_order( broker.Order.Action.BUY, "ige", 1, True) # Adj. Close: 42.09 order.set_good_until_canceled(True) strat.get_broker().place_order(order) # Manually place SPY order to get it filled on the first bar. order = strat.get_broker().create_market_order( broker.Order.Action.SELL_SHORT, "spy", 1, True) # Adj. Close: 105.52 order.set_good_until_canceled(True) strat.get_broker().place_order(order) strat.addOrder(strategy_test.datetime_from_date(2007, 11, 13), strat.get_broker().create_market_order, broker.Order.Action.SELL, "ige", 1, True) # Adj. Close: 127.64 strat.addOrder(strategy_test.datetime_from_date(2007, 11, 13), strat.get_broker().create_market_order, broker.Order.Action.BUY_TO_COVER, "spy", 1, True) # Adj. Close: 147.67 strat.run() self.assertTrue(strat.get_order_updated_events() == 4) self.assertTrue( round(strat.get_broker().get_cash(), 2) == round( initialCash + (127.64 - 42.09) + (105.52 - 147.67), 2))
def testDownloadAndParseDaily(self): instrument = "orcl" barFeed = yahoofeed.Feed() barFeed.addBarsFromCSV( instrument, common.get_data_file_path("orcl-2000-yahoofinance.csv")) strat = sma_crossover.SMACrossOver(barFeed, instrument, 20) plt = plotter.StrategyPlotter(strat, True, True, True) plt.getInstrumentSubplot(instrument).addDataSeries( "sma", strat.getSMA()) strat.run() with common.TmpDir() as tmpPath: fig = plt.buildFigure() fig.set_size_inches(10, 8) png = os.path.join(tmpPath, "plotter_test.png") fig.savefig(png) self.assertEquals( open(common.get_data_file_path("plotter_test.png"), "r").read(), open(png, "r").read())
def testResampledBarFeed(self): barFeed = yahoofeed.Feed() barFeed.addBarsFromCSV("spy", common.get_data_file_path("spy-2010-yahoofinance.csv")) barFeed.addBarsFromCSV("nikkei", common.get_data_file_path("nikkei-2010-yahoofinance.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))
class NinjaTraderTestCase(unittest.TestCase): def __loadIntradayBarFeed(self, timeZone=None): ret = ninjatraderfeed.Feed(ninjatraderfeed.Frequency.MINUTE, timeZone) ret.addBarsFromCSV("spy", common.get_data_file_path("nt-spy-minute-2011.csv")) # This is need to get session close attributes set. Strategy class is responsible for calling this. ret.start() # Process all events to get the dataseries fully loaded. while not ret.stopDispatching(): ret.dispatch() ret.stop() ret.join() return ret def testWithTimezone(self): timeZone = marketsession.USEquities.getTimezone() barFeed = self.__loadIntradayBarFeed(timeZone) ds = barFeed.getDataSeries() for i in xrange(ds.getLength()): currentBar = ds.getValueAbsolute(i) self.assertFalse(dt.datetime_is_naive(currentBar.getDateTime())) def testWithoutTimezone(self): barFeed = self.__loadIntradayBarFeed(None) ds = barFeed.getDataSeries() for i in xrange(ds.getLength()): currentBar = ds.getValueAbsolute(i) # Datetime must be set to UTC. self.assertFalse(dt.datetime_is_naive(currentBar.getDateTime())) def testWithIntegerTimezone(self): try: barFeed = ninjatraderfeed.Feed(ninjatraderfeed.Frequency.MINUTE, -3) self.assertTrue(False, "Exception expected") except Exception, e: self.assertTrue( str(e).find( "timezone as an int parameter is not supported anymore") == 0) try: barFeed = ninjatraderfeed.Feed(ninjatraderfeed.Frequency.MINUTE) barFeed.addBarsFromCSV( "spy", common.get_data_file_path("nt-spy-minute-2011.csv"), -5) self.assertTrue(False, "Exception expected") except Exception, e: self.assertTrue( str(e).find( "timezone as an int parameter is not supported anymore") == 0)
def testOneEvent(self): feed = yahoofeed.Feed() feed.addBarsFromCSV( "orcl", common.get_data_file_path("orcl-2000-yahoofinance.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 testNoTrades(self): barFeed = yahoofeed.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)
class NinjaTraderTestCase(unittest.TestCase): def __loadIntradayBarFeed(self, timeZone=None): ret = ninjatraderfeed.Feed(ninjatraderfeed.Frequency.MINUTE, timeZone) ret.addBarsFromCSV("spy", common.get_data_file_path("nt-spy-minute-2011.csv")) ret.loadAll() return ret def testBaseFeedInterface(self): barFeed = ninjatraderfeed.Feed(ninjatraderfeed.Frequency.MINUTE) barFeed.addBarsFromCSV( "spy", common.get_data_file_path("nt-spy-minute-2011.csv")) feed_test.tstBaseFeedInterface(self, barFeed) def testWithTimezone(self): timeZone = marketsession.USEquities.getTimezone() barFeed = self.__loadIntradayBarFeed(timeZone) ds = barFeed.getDataSeries() for i, currentBar in enumerate(ds): self.assertFalse(dt.datetime_is_naive(currentBar.getDateTime())) self.assertEqual(ds[i].getDateTime(), ds.getDateTimes()[i]) def testWithoutTimezone(self): barFeed = self.__loadIntradayBarFeed(None) ds = barFeed.getDataSeries() for i, currentBar in enumerate(ds): # Datetime must be set to UTC. self.assertFalse(dt.datetime_is_naive(currentBar.getDateTime())) self.assertEqual(ds[i].getDateTime(), ds.getDateTimes()[i]) def testWithIntegerTimezone(self): try: barFeed = ninjatraderfeed.Feed(ninjatraderfeed.Frequency.MINUTE, -3) self.assertTrue(False, "Exception expected") except Exception, e: self.assertTrue( str(e).find( "timezone as an int parameter is not supported anymore") == 0) try: barFeed = ninjatraderfeed.Feed(ninjatraderfeed.Frequency.MINUTE) barFeed.addBarsFromCSV( "spy", common.get_data_file_path("nt-spy-minute-2011.csv"), -5) self.assertTrue(False, "Exception expected") except Exception, e: self.assertTrue( str(e).find( "timezone as an int parameter is not supported anymore") == 0)
def testMapTypeOperations(self): bar_feed = yahoofeed.Feed() bar_feed.add_bars_from_csv(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv"), marketsession.USEquities.getTimezone()) bar_feed.start() for bars in bar_feed: self.assertTrue(YahooTestCase.TestInstrument in bars) self.assertFalse(YahooTestCase.TestInstrument not in bars) bars[YahooTestCase.TestInstrument] with self.assertRaises(KeyError): bars["pirulo"] bar_feed.stop() bar_feed.join()
def testBaseFeedInterface(self): tmpFeed = TemporarySQLiteFeed(SQLiteFeedTestCase.dbName, bar.Frequency.DAY) with tmpFeed: # Load bars using a Yahoo! feed. yahooFeed = yahoofeed.Feed() yahooFeed.addBarsFromCSV( "orcl", common.get_data_file_path("orcl-2000-yahoofinance.csv"), marketsession.USEquities.timezone) yahooFeed.addBarsFromCSV( "orcl", common.get_data_file_path("orcl-2001-yahoofinance.csv"), marketsession.USEquities.timezone) # Fill the database using the bars from the Yahoo! feed. sqliteFeed = tmpFeed.getFeed() sqliteFeed.getDatabase().addBarsFromFeed(yahooFeed) # Load the SQLite feed and process all bars. sqliteFeed.loadBars("orcl") feed_test.tstBaseFeedInterface(self, sqliteFeed)
def testFirstBar(self): initialCash = 1000 barFeed = yahoofeed.Feed() barFeed.addBarsFromCSV(ReturnsTestCase.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, ReturnsTestCase.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)
def execute(cls, args: Args): model_spec = _extract_model_spec(args) xs_file_path = get_data_file_path(model_spec.name, 'x') ys_file_path = get_data_file_path(model_spec.name, 'y') if not os.path.isfile(xs_file_path): save_tensor(model_spec.xs, xs_file_path) print( f'Saved X data for model "{model_spec.name}" to "{xs_file_path}".' ) else: print( f'X data for model `{model_spec.name}` already exists at "{xs_file_path}"' ) if not os.path.isfile(ys_file_path): save_tensor(model_spec.ys, ys_file_path) print( f'Saved Y data for model "{model_spec.name}" to "{ys_file_path}".' ) else: print( f'Y data for model `{model_spec.name}` already exists at "{ys_file_path}"' )
def loadIntradayBarFeed(self): from_month = 1 to_month = 1 from_day = 3 to_day = 3 bar_filter = barfeed.USEquitiesRTH( us_equities_datetime(2011, from_month, from_day, 00, 00), us_equities_datetime(2011, to_month, to_day, 23, 59)) bar_feed = ninjatraderfeed.Feed(bar.Frequency.MINUTE) bar_feed.set_bar_filter(bar_filter) bar_feed.add_bars_from_csv( StrategyTestCase.TestInstrument, common.get_data_file_path("nt-spy-minute-2011.csv")) return bar_feed
def testBounded(self): barFeed = ninjatraderfeed.Feed(ninjatraderfeed.Frequency.MINUTE, maxLen=2) barFeed.addBarsFromCSV("spy", common.get_data_file_path("nt-spy-minute-2011-03.csv")) barFeed.loadAll() barDS = barFeed["spy"] 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)