Пример #1
0
    def testReset(self):
        feed = csvfeed.Feed("Date", "%Y-%m-%d")
        feed.addValuesFromCSV(common.get_data_file_path("orcl-2000-yahoofinance.csv"))

        disp = dispatcher.Dispatcher()
        disp.addSubject(feed)
        disp.run()

        keys = feed.getKeys()
        key = keys[0]
        values = feed[key]

        feed.reset()
        disp = dispatcher.Dispatcher()
        disp.addSubject(feed)
        disp.run()

        reloadedKeys = feed.getKeys()
        reloadedValues = feed[key]

        self.assertEqual(keys.sort(), reloadedKeys.sort())
        self.assertNotEqual(values, reloadedValues)
        self.assertEqual(len(values), len(reloadedValues))
        for i in range(len(values)):
            self.assertEqual(values[i], reloadedValues[i])
Пример #2
0
    def testReset(self):
        key = "i"
        values = [(datetime.datetime.now() + datetime.timedelta(seconds=i), {
            key: i
        }) for i in range(100)]

        feed = memfeed.MemFeed()
        feed.addValues(values)

        disp = dispatcher.Dispatcher()
        disp.addSubject(feed)
        disp.run()

        keys = feed.getKeys()
        values = feed[key]

        feed.reset()
        disp = dispatcher.Dispatcher()
        disp.addSubject(feed)
        disp.run()
        reloadedKeys = feed.getKeys()
        reloadedValues = feed[key]

        self.assertEqual(keys, reloadedKeys)
        self.assertNotEqual(values, reloadedValues)
        self.assertEqual(len(values), len(reloadedValues))
        for i in range(len(values)):
            self.assertEqual(values[i], reloadedValues[i])
Пример #3
0
    def __init__(self, barFeed, broker):
        assert isinstance(barFeed, pyalgotrade.barfeed.BaseBarFeed
                          ), "barFeed is not a subclass of barfeed.BaseBarFeed"
        assert isinstance(broker, pyalgotrade.broker.Broker
                          ), "broker is not a subclass of broker.Broker"

        self.__barFeed = barFeed
        self.__broker = broker
        self.__activePositions = set()
        self.__orderToPosition = {}
        self.__barsProcessedEvent = observer.Event()
        self.__analyzers = []
        self.__namedAnalyzers = {}
        self.__resampledBarFeeds = []
        self.__dispatcher = dispatcher.Dispatcher()
        self.__broker.getOrderUpdatedEvent().subscribe(self.__onOrderEvent)
        self.__barFeed.getNewValuesEvent().subscribe(self.__onBars)
        self.__resultCurrency = "USD"

        # onStart will be called once all subjects are started.
        self.__dispatcher.getStartEvent().subscribe(self.onStart)
        self.__dispatcher.getIdleEvent().subscribe(self.__onIdle)

        # It is important to dispatch broker events before feed events, specially if we're backtesting.
        self.__dispatcher.addSubject(self.__broker)
        self.__dispatcher.addSubject(self.__barFeed)

        # Initialize logging.
        self.__logger = logger.getLogger(BaseStrategy.LOGGER_NAME)
Пример #4
0
    def testFeedWithQuandl(self):
        class RowFilter(csvfeed.RowFilter):
            def includeRow(self, dateTime, values):
                return dateTime.year == 2013

        feed = csvfeed.Feed("Date", "%Y-%m-%d", maxLen=40, timezone=marketsession.USEquities.timezone)
        feed.setRowFilter(RowFilter())
        feed.setTimeDelta(datetime.timedelta(hours=23, minutes=59, seconds=59))
        feed.addValuesFromCSV(os.path.join("samples", "data", "quandl_gold_2.csv"))

        for col in ["USD", "GBP", "EUR"]:
            self.assertEqual(len(feed[col]), 0)

        disp = dispatcher.Dispatcher()
        disp.addSubject(feed)
        disp.run()

        for col in ["USD", "GBP", "EUR"]:
            self.assertEqual(len(feed[col]), 39)

        self.assertEqual(feed["USD"][-1], 1333.0)
        self.assertEqual(feed["GBP"][-1], 831.203)
        self.assertEqual(feed["EUR"][-1], 986.75)
        self.assertFalse(dt.datetime_is_naive(feed["USD"].getDateTimes()[-1]))
        self.assertEqual(
            feed["USD"].getDateTimes()[-1],
            dt.localize(datetime.datetime(2013, 9, 29, 23, 59, 59), marketsession.USEquities.timezone)
        )
Пример #5
0
def resample_impl(barFeed, frequency, csvFile):
    sampler = Sampler(barFeed, frequency, csvFile)

    # Process all bars.
    disp = dispatcher.Dispatcher()
    disp.addSubject(barFeed)
    disp.run()

    sampler.finish()
Пример #6
0
def tstBaseFeedInterface(testCase, feed):
    # This tests the observer.Subject interface.
    disp = dispatcher.Dispatcher()
    disp.addSubject(feed)
    disp.run()

    # This tests the feed.BaseFeed interface.
    feed.createDataSeries("any", 10)
    feed.getNextValues()
Пример #7
0
    def testFeed(self):
        values = [(datetime.datetime.now() + datetime.timedelta(seconds=i), {"i": i}) for i in range(100)]

        feed = memfeed.MemFeed()
        feed.addValues(values)

        # Check that the dataseries are available after adding values.
        self.assertTrue("i" in feed)
        self.assertEqual(len(feed["i"]), 0)
        self.assertFalse("dt" in feed)

        disp = dispatcher.Dispatcher()
        disp.addSubject(feed)
        disp.run()

        self.assertTrue("i" in feed)
        self.assertFalse("dt" in feed)
        self.assertEqual(feed["i"][0], 0)
        self.assertEqual(feed["i"][-1], 99)
Пример #8
0
    def testFeedWithBars(self):
        feed = csvfeed.Feed("Date", "%Y-%m-%d")
        feed.addValuesFromCSV(common.get_data_file_path("orcl-2000-yahoofinance.csv"))

        self.assertEqual(len(feed.getKeys()), 6)
        for col in ["Open", "High", "Low", "Close", "Volume", "Adj Close"]:
            self.assertEqual(len(feed[col]), 0)

        disp = dispatcher.Dispatcher()
        disp.addSubject(feed)
        disp.run()

        for col in ["Open", "High", "Low", "Close", "Volume", "Adj Close"]:
            self.assertEqual(len(feed[col]), 252)

        self.assertEqual(feed["Open"][-1], 30.87)
        self.assertEqual(feed["High"][-1], 31.31)
        self.assertEqual(feed["Low"][-1], 28.69)
        self.assertEqual(feed["Close"][-1], 29.06)
        self.assertEqual(feed["Volume"][-1], 31655500)
        self.assertEqual(feed["Adj Close"][-1], 28.41)
Пример #9
0
    def __init__(self, barFeed, broker):
        self.__feed = barFeed
        self.__broker = broker
        self.__activePositions = set()
        self.__orderToPosition = {}
        self.__barsProcessedEvent = observer.Event()
        self.__analyzers = []
        self.__namedAnalyzers = {}
        self.__dispatcher = dispatcher.Dispatcher()
        self.__broker.getOrderUpdatedEvent().subscribe(self.__onOrderEvent)
        self.__feed.getNewBarsEvent().subscribe(self.__onBars)

        self.__dispatcher.getStartEvent().subscribe(self.onStart)
        self.__dispatcher.getIdleEvent().subscribe(self.onIdle)

        # It is important to dispatch broker events before feed events, specially if we're backtesting.
        self.__dispatcher.addSubject(self.__broker)
        self.__dispatcher.addSubject(self.__feed)

        # Initialize logging.
        self.__logger = logger.getLogger(BaseStrategy.LOGGER_NAME)
Пример #10
0
    def __init__(self, barFeed, broker):
        self.__barFeed = barFeed #ok
        self.__broker = broker #ok
        self.__activePositions = set() #用于管理活动的订单,如已经提交的买单
        self.__orderToPosition = {} ###
        self.__barsProcessedEvent = observer.Event() ###
        self.__analyzers = []
        self.__namedAnalyzers = {}
        self.__resampledBarFeeds = [] #
        self.__dispatcher = dispatcher.Dispatcher() #策略的循环触发机制由该dispatch完成
        self.__broker.getOrderUpdatedEvent().subscribe(self.__onOrderEvent) #__onOrderEvent作为策略和broker之前的桥梁;当订单有变化的时候会通知到这里
        self.__barFeed.getNewValuesEvent().subscribe(self.__onBars) #__onBars作为策略和barfeed之间的桥梁,当bar有变化的时候触发此函数

        self.__dispatcher.getStartEvent().subscribe(self.onStart) #全局的dispatch 启动时候需要调用的
        self.__dispatcher.getIdleEvent().subscribe(self.__onIdle)

        # It is important to dispatch broker events before feed events, specially if we're backtesting.
        self.__dispatcher.addSubject(self.__broker) #把broker加入驱动bus
        self.__dispatcher.addSubject(self.__barFeed) #把bar加入驱动bus

        # Initialize logging.
        self.__logger = logger.getLogger(BaseStrategy.LOGGER_NAME)
Пример #11
0
    def __init__(self, tickFeed, broker):
        self.__tickFeed = tickFeed
        self.__broker = broker
        self.__activePositions = set()
        self.__orderToPosition = {}
        self.__ticksProcessedEvent = observer.Event()
        self.__analyzers = []
        self.__namedAnalyzers = {}
        # self.__resampledTickFeeds = []
        self.__dispatcher = dispatcher.Dispatcher()
        self.__broker.getOrderUpdatedEvent().subscribe(self.__onOrderEvent)
        self.__tickFeed.getNewValuesEvent().subscribe(self.__onTicks)

        # onStart will be called once all subjects are started.
        self.__dispatcher.getStartEvent().subscribe(self.onStart)
        self.__dispatcher.getIdleEvent().subscribe(self.__onIdle)

        # It is important to dispatch broker events before feed events, specially if we're backtesting.
        self.__dispatcher.addSubject(self.__broker)
        self.__dispatcher.addSubject(self.__tickFeed)

        # Initialize logging.
        self.__logger = logger.getLogger(BaseTickStrategy.LOGGER_NAME)
Пример #12
0
    def testBarFeed(self):
        events = {
            "on_bars": False,
            "on_order_book_updated": False,
            "break": False,
            "start": datetime.datetime.now()
        }

        disp = dispatcher.Dispatcher()
        barFeed = barfeed.LiveTradeFeed()
        disp.addSubject(barFeed)

        def on_bars(dateTime, bars):
            bars[common.btc_symbol]
            events["on_bars"] = True
            if events["on_order_book_updated"] is True:
                disp.stop()

        def on_order_book_updated(orderBookUpdate):
            events["on_order_book_updated"] = True
            if events["on_bars"] is True:
                disp.stop()

        def on_idle():
            # Stop after 5 minutes.
            if (datetime.datetime.now() - events["start"]).seconds > 60 * 5:
                disp.stop()

        # Subscribe to events.
        barFeed.getNewValuesEvent().subscribe(on_bars)
        barFeed.getOrderBookUpdateEvent().subscribe(on_order_book_updated)
        disp.getIdleEvent().subscribe(on_idle)
        disp.run()

        # Check that we received both events.
        self.assertTrue(events["on_bars"])
        self.assertTrue(events["on_order_book_updated"])